/**
 *
 * @constructor
 */

$(document).ready(function () {
    window.Program = window.Program || { version: '1.0' }
    // window.daojuNeedDisabledForever = 0;
    String.prototype.gblen = function () {
        var len = 0;
        for (var i = 0; i < this.length; i++) {
            if (this.charCodeAt(i) > 127) {
                len += 2;
            } else {
                len++;
            }
        }
        return len;
    }
    window.isFirstInit = true;
    Program.Model = (function () {
        var constant = {
            uploadUrl: "http://upload.iqiyi.com/image_upload",
            requestUrl: "http://upload.iqiyi.com/request_image_upload",
            file: null
        }

        function getGallery() {
            var $gallery = $("#AlbumEditScreenCorp").find(".gallery");
            return $gallery;
        }

        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL !== undefined) { // basic
                url = window.createObjectURL(file);
            } else if (window.URL !== undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL !== undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        }

        function startUpload(file) {
            var imgsrc, $imgdiv, $bardiv;
            file.uid = Com.string.createUUID();
            imgsrc = getObjectURL(file);
            $bardiv = $('<div class="progress progress-info"><div class="bar" style="width: 0%" /></div>');
            $imgdiv = $('<img class="loading" src="' + imgsrc + '" />');
            $imgdiv.data('loading', true).load(function (e) {
                Com.Image.procThumbnail($(this), 128, 80);
                $(this).unbind('load');
            });
            var $gallery = getGallery();
            $gallery.append($('<li class="item img-' + file.uid + '" />').append($imgdiv, $bardiv));
        }

        function qichuanRequestFile(options, callback) {
            options = options || {};
            constant.file = options.file;
            var headers = options.headers || {};
            $.ajax({
                url: constant.requestUrl + '?t=' + new Date().getTime(),
                dataType: 'json',
                headers: headers,
                method: 'get',
                success: function (data) {
                    if (data && data.code == 'A00000') {
                        callback.call(this, data);
                    } else {
                        console.log('get access fail.');
                        callback.call(this, data);
                    }
                },
                error: function (data) {
                    callback.call(this, data);
                }
            });
        }

        function qichuanUploadFile(options, callback) {
            var fileDetail = constant.file;
            fileDetail.file_id = options.data.file_id;
            var params = {
                url: constant.uploadUrl,
                file: fileDetail,
                headers: {
                    file_id: fileDetail.file_id,
                    file_size: fileDetail.size,
                    range: ('0' + '-' + (fileDetail.size - 1) + ''),
                    businessType: fileDetail.type.split("/")[0]
                }
            };
            var formData = new FormData();
            formData.append('businessType', params.headers['businessType']);
            formData.append('fileid', params.headers['file_id']);
            formData.append('imagefile', params.file);

            $.ajax({
                url: params.url,
                method: "post",
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function (request) {
                    request.setRequestHeader("file_id", params.headers.file_id);
                    request.setRequestHeader("file_size", params.headers.file_size);
                    request.setRequestHeader("range", params.headers.range);
                    request.setRequestHeader("businessType", params.headers.businessType);
                },
                xhr: function () {        //这是关键  获取原生的xhr对象  做以前做的所有事情
                    var xhr = jQuery.ajaxSettings.xhr();
                    xhr.upload.onload = function () {
                        var $imgdiv = getGallery().find('li.img-' + fileDetail.uid);
                        $imgdiv.remove();
                        //$('.button-manual').attr('disabled','disabled');
                        //$('input.uploadButton').attr('disabled','disabled');
                    }

                    xhr.upload.onprogress = function (ev) {
                        if (ev.lengthComputable) {
                            var percent = Math.floor(100 * ev.loaded / ev.total);
                            var $imgdiv = getGallery().find('li.img-' + fileDetail.uid);
                            $imgdiv.find('div.bar').width(percent + '%');
                            if (percent == 100) {
                                $imgdiv.find('div.progress').remove();
                            }
                        }
                    }
                    return xhr;
                },

                data: formData,
                dataType: "json",
                success: function (data) {
                    if (data.code == "A00000") {
                        console.log("success upload");
                        callback.call(this, data);
                    }
                }
            })
        }

        return {
            startRequestFile: qichuanRequestFile,
            startUploadFile: qichuanUploadFile,
            startUpload: startUpload
        }
    })()
})
$(document).ready(function () {
    Program.Config = {
        'defaultOperationTabControl': JSON.stringify(
            [
                {'type': 1, 'display_name': '看更多', 'is_enable': '1', 'is_default': '0'},
                {'type': 0, 'display_name': '聊天室', 'is_enable': '1', 'is_default': '1'},
                {'type': 2, 'display_name': '排行榜', 'is_enable': '0', 'is_default': '0'}
            ]
        ),
        'opActivityNums': ["1", "2", "3"],
        PCAT: null
    }

    Program.memo = {
        "fatherId": 0,
        "id": 0,
        "targetName": "entity",
        "getChannel": "getChannel",
        "getLegoChannel": "getLegoChannel",
        "liveProgramType": "liveProgramType",
        "live_temp_other": "live_temp_other",
        "episodeGradeType": "episodeGradeType",
        "getLegoCategory": "getLegoCategory",
        "from": "library",
        "puyuData": "puyuData",
        "editPic": true,
        "categoryArr": null,
        "defaultOA": "Zb-test",
        "taiwan_oa": "ZB-TW-001"
    }
    Program.Dao = (function () {
        function getDataByName(targetName) {
            var responseData = Program.ajaxManager.findResponseData(targetName);
            return responseData;
        }

        function getChannel() {
            return getDataByName(Program.memo.getChannel).data;
        }

        function getLegoChannel() {
            return getDataByName(Program.memo.getLegoChannel).data;
        }

        function liveProgramType() {
            return getDataByName(Program.memo.liveProgramType);
        }

        function targetName() {
            return getDataByName(Program.memo.targetName);
        }

        function getProgram() {
            var responseData = targetName();
            if (responseData == null || responseData.data == null || responseData.data.totalCount == 0) {
                return null;
            }
            return responseData.data.result[0];
        }

        // 获取大分类
        function getParentCategories(data, callback) {
            var request = genCategoriesRequestStr(0);
            if (Program.Config.PCAT == null) {
                getCategories({
                    request: request
                }, function (json) {
                    Program.Config.PCAT = json;
                    callback.call(this, data);
                });
            } else {
                callback.call(this, data);
            }
        }

        function genCategoriesRequestStr(father_id) {
            var request = {};
            request.url = 'http://xinqi.if.iqiyi.com/basic/categories.json';
            request.type = 'get';
            request.params = {
                father_id: father_id
            };
            return JSON.stringify(request);
        }

        // 获取分类
        function getCategories(data, callback) {
            var options = {
                url: '/api/redirect',
                dataType: 'json',
                data: data,
                method: 'post',
                success: function (data) {
                    callback.call(this, data);
                },
                error: function (data) {
                    callback.call(this, data);
                }
            };
            $.ajax(options);
        }

        var subCategories = [];

        // 根据分类id或取对应中文
        function getSubCategories(ids, callback) {
            var self = this;
            if (ids == '') {
                callback.call(this);
                return;
            }
            var pop_id = ids.shift();
            var _id = pop_id.split('_');
            var pName = '',
                sName = '';
            var request = genCategoriesRequestStr(_id[0]);

            getCategories({
                request: request
            }, function (json) {

                for (var i = 0; i < Program.Config.PCAT.length; i++) {
                    if (Program.Config.PCAT[i].id == _id[0]) {
                        pName = Program.Config.PCAT[i].name;
                        break;
                    }
                }

                for (var i = 0; i < json.length; i++) {
                    if (json[i].id == _id[1]) {
                        sName = json[i].name;
                        break;
                    }
                }

                if (!sName)
                    subCategories.push(pName);
                else
                    subCategories.push(pName + '_' + sName);

                getSubCategories(ids, callback);

            });


        }

        return {
            getChannel: getChannel,
            liveProgramType: liveProgramType,
            targetName: targetName,
            getLegoChannel: getLegoChannel,
            getProgram: getProgram,
            getParentCategories: getParentCategories,
            genCategoriesRequestStr: genCategoriesRequestStr,
            getCategories: getCategories,
            getSubCategories: getSubCategories,
            subCategories: subCategories
        }

    })();

    Program.Validate = (function () {
        function checkNum(checkString) {
            var reg = /^\d+$/
            return reg.test(checkString)
        }

        function checkDateFormat(checkString) {
            var reg = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/
            return reg.test(checkString)
        }

        function defaultHandler(msg) {
            showTips({content: msg, type: "error"});
        }

        function batchCheck(checkArr) {
            if (checkArr == null) {
                checkArr = [];
            }
            if (checkArr.length == 0) {
                return true;
            }
            var flag = false;
            $.each(checkArr, function (index, checkData) {
                flag = baseCheck(checkData);
                if (!flag) {
                    return false;
                }
            })
            return flag;
        }

        function baseCheck(checkData) {
            var flag = false;
            if (!$.isArray(checkData.value)) {
                checkData.value = [checkData.value];
            }
            if (!$.isArray(checkData.error)) {
                checkData.error = [checkData.error];
            }
            if (checkData.handler == null) {
                checkData.handler = defaultHandler;
            }

            $.each(checkData.value, function (index, checkValue) {
                switch (checkData.type) {
                    case "date":
                        flag = checkDateFormat(checkValue);
                        break;
                    case "not_empty":
                        flag = checkValue != null && checkValue != "";
                        break;
                    case "eq":
                        flag = checkValue == checkData.other;
                        break;
                    case "ne":
                        flag = checkValue != checkData.other;
                        break;
                    case "gt":
                        flag = checkValue > checkData.other;
                        break;
                    case "ge":
                        flag = checkValue >= checkData.other;
                        break;
                    case "lt":
                        flag = checkValue < checkData.other;
                        break;
                    case "le":
                        flag = checkValue <= checkData.other;
                        break;
                    case "number":
                        flag = checkNum(checkValue)
                        break;
                    case "endsWith":
                        flag = checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                        break;
                    case "define":
                        flag = checkData.regHandler(checkData);
                        break;
                    default :
                        break;
                }
                if (!flag) {
                    var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                    checkData.handler(hint);
                    return false;
                }
            })
            return flag
        }

        return {
            baseCheck: baseCheck,
            batchCheck: batchCheck,
            checkDateFormat: checkDateFormat,
            checkNum: checkNum
        }
    })();
    Program.Service = (function () {
        function prepareSingleItem(regName, fatherId, type, filterZero, filterEmpty) {
            var singleValue = $.trim($(regName).suggest("getValue"));
            var isNum = Program.Validate.checkNum(singleValue)
            if (!isNum) {
                return null;
            }
            if (filterEmpty) {
                if ($.trim($(regName).val()) == "") {
                    return null;
                }
            }
            if (filterZero) {
                if (singleValue === '0') {
                    return null;
                }
            }
            var retData = {fatherId: fatherId, "key": parseInt(singleValue), type: type, "value": "" };
            if (type == 7) {
                retData.value = $(regName).val();
            }
            return retData;
        }

        function prepareMultipleItem(regName, fatherId, type, needValue) {
            var relationList = [];
            needValue = needValue ? true : false;
            var items = $(regName).suggest("getItems");
            $.each(items, function (index, element) {
                if (element.id != null) {
                    relationList.push({fatherId: fatherId, "key": element.id, type: type, "value": needValue ? element.label : "" });
                }
            });
            return relationList
        }

        function prepareRelation(entityType) {
            var relationList = [];
            var channelEntity = Program.Dao.getChannel();
            if (channelEntity == null) {
                return
            }
            var _fatherId = channelEntity.id;
            relationList = relationList.concat(prepareMultipleItem('#ajaxSuggest', _fatherId, 1, true));
            var item = [];
            if (entityType == 1) {
                $("input[name=base_3_team]").each(function (index, target) {
                    var $target = $(target)
                    var $targetValue = $target.val();
                    if ($.trim($targetValue).length > 0) {
                        var $scoreValue = $target.parent().find("input[name=base_3_score]").val();
                        if ($.trim($scoreValue).length == 0 || isNaN($scoreValue)) {
                            $scoreValue = 0;
                        } else {
                            $scoreValue = parseInt($scoreValue);
                        }
                        relationList.push({fatherId: _fatherId, "key": $scoreValue, type: 3, "value": $targetValue })
                    }
                })
            }
            item = prepareSingleItem("input[name=playbackSuggest]", _fatherId, 7, true);
            if (item != null) {
                relationList.push(item);
            }

            item = prepareSingleItem("#votePK", _fatherId, 106, true, true);
            if (item != null) {
                relationList.push(item);
            }
            item = prepareSingleItem("#voteRank", _fatherId, 107, true, true);
            if (item != null) {
                relationList.push(item);
            }

            var keySelect = $("select[name=frontSuggestType]").val();
            if (keySelect == "simple-video") {
                relationList = relationList.concat(prepareMultipleItem('#appendFront_' + keySelect, _fatherId, 5, true));
            } else {
                item = prepareSingleItem('#appendFront_' + keySelect, _fatherId, 5)
                if (item != null) {
                    relationList.push(item);
                }
            }
            keySelect = $("select[name=endSuggestType]").val();
            if (keySelect == "simple-video") {
                relationList = relationList.concat(prepareMultipleItem('#appendEnd_' + keySelect, _fatherId, 6, true));
            } else {
                item = prepareSingleItem('#appendEnd_' + keySelect, _fatherId, 6)
                if (item != null) {
                    relationList.push(item);
                }
            }
            if (2 == channelEntity.liveType) {
                var live_tmp_other = $("#live_temp_other").val();
                if (live_tmp_other.length > 0) {
                    relationList.push({fatherId: _fatherId, key: 0, type: 201, value: live_tmp_other });
                }
                // relate passport id
                var passportId = {uid: $.trim($("input[name=uid_hidden]").val()), nickname: $.trim($("input[name=nickname_hidden]").val())};
                if (passportId.uid.length > 0 && passportId.nickname.length > 0) {
                    var type301 = {fatherId: _fatherId, key: 0, type: 301, value: passportId.uid };
                    var type302 = {fatherId: _fatherId, key: 0, type: 302, value: passportId.nickname };
                    var dataValid = false;
                    if ($("select[name=passport_select]").val() == "option_uid") {
                        type301.key = 1;
                        dataValid = $.trim($("input[name=passport_uid]").val()) == type301.value;
                        console.log(" passport id 验证失效 " + JSON.stringify(type301) + "  ; " + $.trim($("input[name=passport_uid]").val()));
                    } else if ($("select[name=passport_select]").val() == "option_nickname") {
                        type302.key = 1;
                        dataValid = $.trim($("input[name=passport_nickname]").val()) == type302.value;
                        console.log(" passport id 验证失效 " + JSON.stringify(type302) + "  ; " + $.trim($("input[name=passport_nickname]").val()));
                    }
                    if (dataValid) {
                        relationList.push(type301);
                        relationList.push(type302);
                    } else {
                        console.log(" passport id 验证失效 " + JSON.stringify(type301) + ";" + JSON.stringify(type302));
                    }
                }

                // 关联圈子 去除47结尾
                var items = $("#paopaoSuggest").suggest("getItems");
                $.each(items, function (index, element) {
                    if (element.id != null) {
                        relationList.push({fatherId: _fatherId, "key": element.id / 100 >> 0, type: 401, "value": element.label});
                    }
                });
            }
            return relationList;
        }

        function prepareModel() {
            var entityId = Program.memo.id;
            var entity = {};
            if (entityId > 0) {
                entity.id = parseInt(entityId);
                var programEntity = Program.Dao.getProgram();
                entity.updateTime = programEntity.updateTime;
                entity.fatherId = $("#fatherId").val();
                entity.oaDocNo = programEntity.oaDocNo
                entity.needOA = 0;
            } else {
                entity.fatherId = $("#fatherId").val();
                entity.needOA = 1;
            }
            entity.pname = $("#pname").val();
            entity.startPlayTime = $("#startPlayTime").val();
            entity.endPlayTime = $("#endPlayTime").val();
            entity.streamStartPlayTime = $("#streamStartPlayTime").val();
            entity.streamEndPlayTime = $("#streamEndPlayTime").val();
            entity.qitanId = $("#qitanId").val();
            entity.waterMarkFlag = $('input:radio[name=waterMarkFlag]:checked').val() == 1 ? true : false;
            var logHiddenJson = {};
            $("input[name='logoHidden']:checkbox:checked").each(function () {
                var key = $(this).attr("keyName");
                var value = $(this).val();
                logHiddenJson[key] = value;
            })
            entity.logoHidden = JSON.stringify(logHiddenJson);

            entity.subscribe = $("input[name=subscribe]:checked").val();
            entity.allowPopups = $('input:radio[name=dan_mu]:checked').val() == 1 ? true : false;
            entity.freeStatus = true;
            entity.vipType = parseInt($("input:radio[name=vipType]:checked").val());
            entity.weiboTopic = $("input[name=weiboTopic]").val();
            entity.leftChannel = "";
            entity.audioChannel = "";
            entity.videoPieceLength = 0;
            entity.rightChannel = "";
            entity.description = $("#description").val();
            entity.type = $("#type").val();
            entity.orderBy = 1000;
            entity.allowComment = $("input:radio[name=qitanMarkFlag]:checked").val() == 1 ? true : false;
            entity.logoUrl = "";
            entity.relationList = prepareRelation(entity.type);
            entity.qiyiProduct = $("input:radio[name=qiyiProduct]:checked").val() == 1 ? true : false;
            entity.qiyiExclusive = $("input:radio[name=qiyiExclusive]:checked").val() == 1 ? true : false;
            entity.barCode = "";
            entity.episodeGrade = parseInt($("select[name=episodeGrade]").val());
            if (isNaN(entity.episodeGrade)) {
                entity.episodeGrade = 0;
            }
            entity.daojuEnable = $('input:radio[name=daojuFlag]:checked').val();
            entity.daojuId = $('#daojuId').data('id');
            entity.daojuName = $('#daojuId').val();
            entity.daojuStarCheck = makeStarList(entity.daojuEnable);
            entity.daojuStar = JSON.stringify(entity.daojuStarCheck);
            entity.userName = $('header a.name').html();
            //add displayRecommend by justin 2018.1.12
            entity.displayRecommend = $('input:radio[name=is_dispaly_recommend]:checked').val();
            entity.chatEnable = $('input:radio[name=chat_enable]:checked').val();
            entity.chatDisplay = $('input:radio[name=chat_display]:checked').val();
            if (parseInt(entity.chatEnable) == 0) {
                entity.chatDisplay = "0"
            }
            entity.chatFake = $('input:radio[name=chat_fake]:checked').val();
            entity.chatPopups = $('input:radio[name=chat_popups]:checked').val();
            entity.checkType = $('input:radio[name=check_type]:checked').val()
            entity.chatRights = $('select[name=chatRights]').val();
            entity.chatRoomId = 0;
            entity.category = "[]";
            entity.uid = Number($("input[name=hidden_uid]").val());
            entity.recommendRate = parseInt($("select[name=recommendRate]").val())
            entity.hot = parseInt($('input:radio[name=hot]:checked').val())
            entity.test = parseInt($('input:radio[name=test]:checked').val());
            entity.directorEnable = $('input:radio[name=director_enable]:checked').val()
            //dbt_region 赋值
            var dbtRegion_val = $('input:radio[name=dbt_region]:checked').val();
            if (dbtRegion_val == 0) {
                entity.dbtRegion = "bj";
            } else if (dbtRegion_val == 1) {
                entity.dbtRegion = "sh";
            } else if (dbtRegion_val == 2) {
                entity.dbtRegion = "tw";
            } else {
                entity.dbtRegion = "bj";
            }

            if ($("input[name=recommendRemark]").val().length > 0) {
                entity.recommendRemark = $("input[name=recommendRemark]").val();
            }
            if ($.trim($("input[name=subjectUrl]").val()).length > 0) {
                entity.subjectUrl = $.trim($("input[name=subjectUrl]").val());
            }
            entity.projectType = $("select[name=project_type_select]").val();
            entity.resourceId = $("input[name=resourceId]").val();
            entity.snapShotType = $('input:radio[name=snap_shot_type]:checked').val();
            entity.snapShotGap = -1;
            if (entity.snapShotType == 1) {
                entity.snapShotGap = $('select[name=snapshot_gap_select]').val();
            }
            entity.publicLevel = 0;
            if ($('input:radio[name=public_level]').is(":checked")) {
                entity.publicLevel = $('input:radio[name=public_level]:checked').val();
            }
            entity.programTag = makeUpProgramTag();
            var channelEntity = Program.Dao.getChannel();
            if (channelEntity == null) {
                return
            }
            if (channelEntity.liveType == 2) {
                entity.categoryCheck = makeUpCategory();
                entity.category = JSON.stringify(entity.categoryCheck);
                entity.freeStatus = $('input:radio[name=freeStatus]:checked').val() == 1 ? true : false;
            }
            var matchSummary = makeUpMatchSummary();
            if (matchSummary != null) {
                entity.matchSummary = matchSummary;
            }

            entity.tabControls = Program.View.opGetData();
            if (entityId == 0) {
                if ($("#oaSuggest").suggest("getValue") == "") {
                    if (entity.test == 1) {
                        entity.oaDocNo = Program.memo.defaultOA;
                    }
                } else {
                    var suggestData = $("#oaSuggest").data("suggestData");
                    if (suggestData.docNo == $("#oaSuggest").suggest("getValue")) {
                        entity.oaDocNo = suggestData.docNo;
                        entity.oaDocUrl = suggestData.toDocDetailsUrl;
                        entity.oaDocEditorStatus = suggestData.chiefEditorApprovalStatus;
                    }
                }
            }

            return entity;
        }

        function makeStarList(daojuEnable) {
            var daojuStar = {};
            var starList = [];
            if (daojuEnable == 1) {  //使用道具
                var daojuStarFlag = $("input[name=daojuStarFlag]:checked").val();
                if (daojuStarFlag == 0) {   // 单明星
                    var $addSingleStar = $("#addSingleStar");
                    var show_name = $addSingleStar.find("input[name=daojuStar]").val();
                    var id = $addSingleStar.find("input[name=daojuStarId]").val();
                    var show_pic = $addSingleStar.find("input[name=daojuStarImg]").val();
                    var jsonStar = {};
                    if (id == "") {
                        jsonStar = {show_name: show_name, show_pic: show_pic};
                    } else {
                        jsonStar = {id: parseInt(id), show_name: show_name, show_pic: show_pic};
                    }
                    starList.push(jsonStar);
                } else {                    // 多明星
                    var $addMoreStar = $("#addMoreStar");
                    $addMoreStar.find(".control-group").each(function () {
                        var show_name = $(this).find("input[name=daojuStar]").val();
                        var id = $(this).find("input[name=daojuStarId]").val();
                        var show_pic = $(this).find("input[name=daojuStarImg]").val();
                        //if (show_name != "" || show_pic != "") {
                        if (id == "") {
                            jsonStar = {show_name: show_name, show_pic: show_pic};
                        } else {
                            jsonStar = {id: parseInt(id), show_name: show_name, show_pic: show_pic};
                        }
                        starList.push(jsonStar);
                        //}
                    });
                }
                daojuStar = {daojuStarFlag: daojuStarFlag, starList: starList};
                return daojuStar;
            } else {
                return daojuStar;
            }
        }

        function makeUpCategory() {
            var category = [];
            var rootId = Number($("#channelCateTag").val());
            category.push({id: rootId, level: 1 });
            var secArr = $("input[name=sec_category]:checked");
            var jElement = null;
            $.each(secArr, function (i, element) {
                jElement = $(element);
                category.push({id: parseInt(jElement.val()), pid: rootId, name: jElement.attr("data-name"), level: 2});
            });
            var thirdArr = $("input[name=third_category]:checked");
            $.each(thirdArr, function (i, element) {
                jElement = $(element);
                category.push({ pid: parseInt(jElement.attr("data-pid")), id: jElement.val(), name: jElement.attr("data-name"), level: 3});
            });
            // makeup tag
            var labelArr = $("input[name=ep_tag_label]:checked");
            if (labelArr.length > 0) {
                $.each(labelArr, function (i, element) {
                    jElement = $(element);
                    category.push({  id: jElement.val(), name: jElement.attr("data-name"), dataMode: 1});
                })
            }
            return category
        }

        function makeUpProgramTag() {
            if ($("span.tagshow").text() == "") {
                return "";
            }
            return  $("input[name=tag]").val();
        }

        function makeUpMatchSummary() {
            var obj = {id: 0, title: "", start: 0}
            var targetId = $("#relationSportId").suggest("getValue");
            var targetName = $("#relationSportId").val();
            var bindName = $("#relationSportId").attr("bind-data-title");
            if (targetName.length > 0 && targetName != bindName) {
                return {error: true, msg: "关联赛程库数据非法"};
            }
            if (targetId == "") {
                return null;
            }
            obj.id = Number(targetId);
            obj.title = bindName;
            obj.start = Number($("#relationSportId").attr("bind-data-matchStartTime"));
            return JSON.stringify(obj);
        }

        function getSendImageData() {
            var sumbitImgData = {};
            sumbitImgData.imageDatas = [];
            var imageData = {"materials": [], "images": [], "contentRank": "0", "useType": "699"}
            sumbitImgData.imageDatas.push(imageData);
            var cropValues = $("#AlbumEditScreenCorp").imagecrop("getValue");
            console.log(JSON.stringify(cropValues));
            $(".item img").each(function (i, imgTarget) {
                imageData.materials.push(Program.Formatter.imageMaterial($(imgTarget)))
            });
            for (var key in cropValues) {
                imageData.images.push(Program.Formatter.imageCrop(cropValues[key]))
            }
            if (imageData.materials.length == 0 && imageData.images.length == null) {
                return null;
            }
            return sumbitImgData.imageDatas;
        }


        function submitHandler(type, skipDaoju) {

            var channelEntity = Program.Dao.getChannel();
            var modelData = prepareModel();
            if ($.trim($("#votePK").val()) != "" && $("#votePK").val() != $("#votePK").suggest("getValue")) {
                showTips({content: "PK投票 不允许手动修改！", type: "error"});
                return;
            }
            if ($.trim($("#voteRank").val()) != "" && $("#voteRank").val() != $("#voteRank").suggest("getValue")) {
                showTips({content: "列表投票 不允许手动修改！", type: "error"});
                return;
            }
            if (modelData.matchSummary != null && Object.prototype.hasOwnProperty.call(modelData.matchSummary, "error")) {
                showTips({content: modelData.matchSummary.msg, type: "error"});
                return;
            }
            if (channelEntity != null) {
                if (channelEntity.liveType == 2) {
                    if (type == "save" && modelData.test == 0) {
                        if ($("#oaSuggest").suggest("getValue") == "") {
                            showTips({content: "oa-单据不能为空", type: "error"});
                            return
                        }
                    }
                    if (!checkLiveType(modelData)) {
                        return;
                    }
                }
            }

            if (!jQuery.isEmptyObject(modelData.daojuStarCheck)) {
                var daojuStarFlag = modelData.daojuStarCheck.daojuStarFlag;
                var starList = modelData.daojuStarCheck.starList;
                if (daojuStarFlag == 0) {   //单明星
                    if (starList[0].show_name == null || starList[0].show_name == undefined || starList[0].show_name == "") {
                        showTips({content: "单明星模式下，渠道明星不能为空", type: "error"});
                        return;
                    }
                    if (starList[0].show_name.length > 8) {
                        showTips({content: "单明星模式下，渠道明星长度不能超过16个字符（8个中文字）", type: "error"});
                        return;
                    }

                } else {                    //多明星
                    var flag = false;
                    $.each(starList, function (i, element) {
                        if (i == 0 && (element.show_name == "" || element.show_pic == "")) {
                            showTips({content: "多明星模式下，第一组渠道明星和明星图片地址不能为空", type: "error"});
                            flag = true;
                            return false;
                        } else if ((element.show_name != "" && element.show_pic == "") || (element.show_name == "" && element.show_pic != "")) {
                            showTips({content: "多明星模式下，渠道明星和明星图片，其中之一不能有空缺，要么都不填，要么都填", type: "error"});
                            flag = true;
                            return false;
                        }
                    });
                    if (flag) {
                        return;
                    }
                }
                delete modelData.daojuStarCheck;
            }

            if (Program.View.opGetData() == "") {
                return;
            }

            if (!checkModel(modelData)) {
                return;
            }
            $("button[type=submit]").prop("disabled", "disabled")
            Program.RemoteCheck.doCheck(null, function (data) {
                    var allSuccess = true;
                    var errorMsg = [];
                    if (data != null) {
                        $.each(data, function (index, element) {
                            if (!element.success) {
                                allSuccess = false;
                                errorMsg.push(element.msg);
                            }
                        });
                    }
                    if (!allSuccess) {
                        showTips({
                            content: errorMsg.join("\n"),
                            type: "error"
                        })
                        //   $(document).tips()
                        $("button[type=submit]").removeAttr("disabled");
                        return;
                    }

                    if (type == "save" && channelEntity.liveType == 2) {
                        if (modelData.daojuEnable == 0 && skipDaoju != true) {
                            $("#oepn-item-dlg").dialog("open");
                            $("button[type=submit]").removeAttr("disabled");
                            return;
                        }
                    }
                    var sendImageDatas = null;
                    if (Program.memo.id == 0 || Program.memo.editPic) {
                        sendImageDatas = getSendImageData();
                    }
                    var task = Program.Task.sendTask(modelData, sendImageDatas);
                    task.regName = type == "edit" ? "editData" : "saveData";
                    task.options.url = type == "edit" ? Program.urlConfig.programEdit : Program.urlConfig.programAdd;
                    Program.ajaxManager.push(task.regName, task.options, null, true);
                    Program.ajaxManager.startLoad();
                },
                function startRemoveCheck(saveData) {
                    if (saveData != null) {
                        $.each(saveData, function (index, element) {
                            var requestData = {url: Program.urlConfig.getQiPuBaseUrl(element.value), type: "get"};
                            $.ajax({
                                url: Program.urlConfig.redirect,
                                type: "post",
                                dataType: "json",
                                data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                                success: function (data) {
                                    console.log("data" + JSON.stringify(data))
                                    element.complete = true;
                                    if (data != null && data.hasOwnProperty("id")) {
                                        element.success = true;
                                        if (data["episode_summary"] != null && data["episode_summary"].length > 200) {
                                            element.success = false;
                                            element.msg = "奇谱ID：" + element.value + " 关联节目超过200个!";
                                        }
                                    } else {
                                        element.success = false;
                                        element.msg = "验证失败:" + element.value;
                                    }
                                    console.log("element.msg" + element.msg);
                                },
                                error: function (data) {
                                    element.complete = true;
                                    element.success = false;
                                    element.msg = "检测请求失败:" + element.value;
                                    console.log("data" + JSON.stringify(data) + ";" + element.msg)
                                }
                            })
                        })
                    }
                }
            )
        }

        function checkLiveType(modelData) {
            var checkArr = [];
            //checkArr.push({value: $('select[name=project_type_select]').val().length , error: "请选择项目类型", type: "gt", other: 0 })
            if (modelData.resourceId.length > 0) {
                checkArr.push({value: modelData.resourceId, error: "资源位Id格式错误", type: "endsWith", other: "12" })
            }
            checkArr.push({value: $("input[name=ep_tag_label]:checked").length, error: "必须选择标签！", type: "gt", other: 0 })
            checkArr.push({value: modelData.programTag.length, error: "大小分类不能为空！", type: "gt", other: 0 })
            checkArr.push({value: $('select[name=project_type_select]').val().length, error: "请选择项目类型", type: "gt", other: 0 })
            checkArr.push({value: $('#episodeGrade').val().length, error: "节目等级不能为空", type: "gt", other: 0 });
            checkArr.push({value: $("input:radio[name=use_puyu_radio]:checked").val(), error: "必须选择关联璞玉信息", type: "not_empty" });
            if ($("input:radio[name=use_puyu_radio]:checked").val() == 1) {
                checkArr.push({value: $("input[name=suggest_barCode]").val().length, error: "尚未设置关联璞玉信息", type: "gt", other: 0 });
                checkArr.push({value: $("input[name=suggest_barCode]").val(), error: "璞玉条形码与数据不一致", type: "eq", other: $("input[name=puyu_barCode]").val() });
                modelData.barCode = $("input[name=puyu_barCode]").val();
            }
            if (!Program.Validate.batchCheck(checkArr)) {
                console.log("interrupt checkLiveType checkRepeat")
                return false;
            }
            var checkLevel1 = false;
            var checkLevel2 = false;
            var checkLevel3 = false;
            var hasThirdCategory = $("input[name=third_category]");
            if (hasThirdCategory.length == 0) {
                checkLevel3 = true;
            }
            if (modelData.categoryCheck != null) {
                $.each(modelData.categoryCheck, function (i, element) {
                    if (element.level == 1) {
                        checkLevel1 = true;
                    }
                    if (element.level == 2) {
                        checkLevel2 = true;
                    }
                    if (element.level == 3) {
                        checkLevel3 = true;
                    }
                })
            }
            if (!checkLevel2) {
                showTips({content: "必须选择一个二级分类", type: "error"});
                return false;
            }
            if (!checkLevel3) {
                showTips({content: "必须选择一个三级分类", type: "error"});
                return false;
            }
            return true;
        }

        function checkModel(modelData) {
            Program.RemoteCheck.clear();
            var checkArr = [];
            var frontValue = $("select[name=frontSuggestType]").val();
            var endValue = $("select[name=endSuggestType]").val();
            var items = null;
            if (frontValue == "simple-video") {
                items = $('#appendFront_' + frontValue).suggest("getItems");
                checkArr.push({value: items.length, error: "数量不能大于200", type: "le", other: 200})
            } else {
                if ($('#appendFront_' + frontValue).val().length > 0) {
                    checkArr.push({value: $('#appendFront_' + frontValue).val(), error: "节目集锦需要数字格式", type: "number"});
                    if ("album" == frontValue) {
                        checkArr.push({value: $('#appendFront_' + frontValue).val(), error: "专辑qipuId格式错误", type: "endsWith", other: "01"});
                    } else if ("playlist" == frontValue) {
                        checkArr.push({value: $('#appendFront_' + frontValue).val(), error: "播单qipuId格式错误", type: "endsWith", other: "02"});
                    }
                    Program.RemoteCheck.addToCheck({regName: '#appendFront_' + frontValue, value: $('#appendFront_' + frontValue).val(), modeType: frontValue })
                }

            }
            if (endValue == "simple-video") {
                items = $('#appendEnd_' + endValue).suggest("getItems");
                checkArr.push({value: items.length, error: "数量不能大于200", type: "le", other: 200})
            } else {
                if ($('#appendEnd_' + frontValue).val().length > 0) {
                    checkArr.push({value: $('#appendEnd_' + frontValue).val(), error: "节目集锦需要数字格式", type: "number"})
                    if ("album" == frontValue) {
                        checkArr.push({value: $('#appendEnd_' + frontValue).val(), error: "专辑qipuId格式错误", type: "endsWith", other: "01"});
                    } else if ("playlist" == frontValue) {
                        checkArr.push({value: $('#appendEnd_' + frontValue).val(), error: "播单qipuId格式错误", type: "endsWith", other: "02"});
                    }
                    Program.RemoteCheck.addToCheck({regName: '#appendEnd_' + frontValue, value: $('#appendEnd_' + frontValue).val(), modeType: frontValue })
                }
            }

            if (!Program.Validate.batchCheck(checkArr)) {
                console.log("interrupt checkRepeat")
                return false;
            }

            checkArr = [];
            checkArr.push({value: [modelData.streamStartPlayTime, modelData.streamEndPlayTime, modelData.startPlayTime, modelData.endPlayTime, modelData.pname], error: "请填写完整", type: "not_empty"});
            checkArr.push({value: [modelData.startPlayTime, modelData.endPlayTime, modelData.streamStartPlayTime, modelData.streamEndPlayTime], error: ["节目开始时间日期格式错误", "节目结束时间日期格式错误", "流开始时间日期格式错误", "流结束时间日期格式错误"], type: "date"});
            checkArr.push({value: modelData.pname.length, error: "节目名称长度不能超过40", type: "le", other: 40 })
            checkArr.push({value: modelData.endPlayTime, error: "节目结束时间需要大于节目开始时间", type: "gt", other: modelData.startPlayTime});
            checkArr.push({value: modelData.streamEndPlayTime, error: "流结束时间需要大于流开始时间", type: "gt", other: modelData.streamStartPlayTime});
            checkArr.push({value: modelData.streamEndPlayTime, error: "流结束时间不能小于节目结束时间", type: "ge", other: modelData.endPlayTime});
            checkArr.push({value: modelData.streamStartPlayTime, error: "流开始时间不能大于节目开始时间", type: "le", other: modelData.startPlayTime});
            checkArr.push({value: modelData.subjectUrl, error: "专题页url格式错误,请修改后保存!", type: "define", regHandler: function (checkData) {
                if (modelData.subjectUrl == null || modelData.subjectUrl.length == 0) {
                    return true;
                }
                return modelData.subjectUrl.split('://')[0] === 'http';
            }});
            if (!Program.Validate.batchCheck(checkArr)) {
                console.log("interrupt checkRepeat")
                return false;
            }
            var channelEntity = Program.Dao.getChannel();
            var checkProgram = (new Date(modelData.endPlayTime.replace(/-/g, "/")).getTime() - new Date(modelData.startPlayTime.replace(/-/g, "/")).getTime()) / 1000;
            if (channelEntity.maxPlaybackPeriod < checkProgram) {
                console.log("checkProgram:" + checkProgram + ";maxPlaybackPeriod:" + channelEntity.maxPlaybackPeriod);
                SystemDialog.queryAlert("回看时间必须大于或等于节目时间<br>无法完成提交，请先修改回看时间！");
                return false;
            }
            return true;
        }

        return  {
            checkModel: checkModel,
            submitHandler: submitHandler
        }
    })();
    Program.RemoteCheck = (function () {
        var timerId = -1;
        var _handler = null;
        var _startHandler = null;
        var _data = [];

        function startCheck() {
            _startHandler.call(this, _data);
            return setInterval(checkComplete, 1000);
        }

        function checkComplete() {
            var allComplete = true;
            $.each(_data, function (index, element) {
                if (!element.complete) {
                    allComplete = false
                    return true;
                }
            })
            if (allComplete) {
                clearInterval(timerId);
                timerId = -1;
                console.log("check data over");
                _handler(_data);
            }
        }

        function doCheck(data, handler, startHandler) {
            if (timerId > 0) {
                console.log("wait to remote check")
                return;
            }
            _handler = handler;
            _startHandler = startHandler;
            if (data != null) {
                if ($.isArray(data)) {
                    _data = data;
                } else {
                    _data = [data];
                }
            }
            if (_data == null || _data.length == 0) {
                handler.call(null)
                return;
            }

            if (timerId < 0) {
                timerId = startCheck();
            }
        }

        function clear() {
            _data = [];
        }

        function addToCheck(checkData) {
            _data.push(checkData)
        }

        return{
            clear: clear,
            doCheck: doCheck,
            addToCheck: addToCheck
        }
    })();


    Program.Task = (function () {
        function getGradeTypeHandler(data) {
            var selectJDom = $("select[name=episodeGrade]");
            $("<option>", {value: "", html: "请选择"}).appendTo(selectJDom);
            $.each(data.data, function (index, obj) {
                $("<option>", {
                    value: obj.key,
                    html: obj.descr
                }).appendTo(selectJDom);
            });
        }

        function getGradeType() {
            return {
                regName: Program.memo.episodeGradeType,
                options: {
                    type: "get",
                    url: Program.urlConfig.configs,
                    dataType: "json",
                    data: {type: "EpisodeGradeType"},
                    success: function (data) {
                        getGradeTypeHandler(data);
                    }
                }
            }
        }

        function getChannel(fatherId) {
            return {
                regName: Program.memo.getChannel,
                options: {
                    type: "post",
                    url: Program.urlConfig.channelGet,
                    dataType: "json",
                    data: {id: fatherId}
                }
            }
        }

        function getWarnMsg(warnObj) {
            var htmlArr = [];
            if (warnObj.sportBind != null && warnObj.sportBind < 0) {
                var bindValue = 0 - warnObj.sportBind;
                if (bindValue % 10 == 1) {
                    htmlArr.push("移除旧赛程库关联失败")
                }
                if (bindValue >= 10) {
                    htmlArr.push("添加新赛程库关联失败")
                }
            }
            return htmlArr
        }

        var sendTaskCallFunc = function (data) {
            showTips({content: data.msg});
            if (data.code == "A00000") {
                var timeOutTime = 2000;
                var htmlArr = getWarnMsg(data.data);
                if (htmlArr.length > 0) {
                    timeOutTime += 1500;
                    SystemDialog.queryAlert("保存成功<br>" + htmlArr.join("<br>"));
                }
                setTimeout(function () {
                    var toUrl = null;
                    if (Program.memo.from == "list") {
                        toUrl = "/epg/program_list.html?fatherId=" + Program.memo.fatherId;
                    } else if (Program.memo.from == "library") {
                        toUrl = "/epg/program_library.html";
                    } else if (Program.memo.from == "carousel") {
                        toUrl = "/epg/carousel_edit.html?fatherId=" + Program.memo.fatherId;
                    }
                    window.location.href = toUrl;
                }, timeOutTime)
            } else {
                $("button[type=submit]").removeAttr("disabled");
            }
        }

        function sendTask(modelData, sendImageDatas) {
            return {
                regName: null,
                options: {
                    type: "post",
                    dataType: "json",
                    data: {"data": JSON.stringify(modelData), "imageDatas": sendImageDatas == null ? null : JSON.stringify(sendImageDatas) },
                    success: sendTaskCallFunc,
                    error: function (data) {

                    }

                }
            }
        }


        function getLiveProgramType() {
            return {
                regName: Program.memo.liveProgramType,
                options: {
                    type: "get",
                    url: Program.urlConfig.configs,
                    dataType: "json",
                    data: {type: "LiveProgramType"}
                    //success: getLiveProgramTypeHandler
                }
            }
        }

        function getLiveTmpOtherType() {
            return {
                regName: Program.memo.live_temp_other,
                options: {
                    type: "get",
                    url: Program.urlConfig.configs,
                    dataType: "json",
                    data: {type: Program.memo.live_temp_other},
                    success: function (data) {
                        var selectJDom = $("#" + Program.memo.live_temp_other);
                        $.each(data.data, function (index, obj) {
                            $("<option>", {
                                value: obj.val,
                                html: obj.descr
                            }).appendTo(selectJDom);
                        });
                    }
                }
            }
        }

        function getLegoChannelTypeHandler(data) {
            var selectJDom = $("#channelCateTag");
            $.each(data.data, function (index, obj) {
                $("<option>", {
                    value: obj.key,
                    html: obj.val
                }).appendTo(selectJDom);
            });
        }

        function getLegoChannelType() {
            return {
                regName: Program.memo.getLegoChannel,
                options: {
                    type: "get",
                    url: Program.urlConfig.configs,
                    dataType: "json",
                    data: {type: "category_use"},
                    success: getLegoChannelTypeHandler
                }
            }
        }

        function getLegoCategory() {
            // 线上固定获取 channeld 93 直播标签
            var channelId = 93;
            var requestData = {url: Program.Constant.thirdUrl_category_first_list_url, type: "get", params: {channel_id: channelId, liveDisplay: 1, liveUsed: 1}, needCookie: true};
            var toParent = $("#ep_tag_zone");
            var option = {
                url: Program.urlConfig.redirect,
                type: "post",
                dataType: "json",
                data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                success: function (data) {
                    toParent.html("");
                    //.html("");
                    if (data != null && data.data != null && data.data.channelData != null) {
                        $.each(data.data.channelData, function (i, element) {
                            $('<label style="display: inline;margin-left: 5px"><input type="checkbox" data-name="' + element.categoryName + '"  name="ep_tag_label" value="' + element.categoryId + '">' + element.categoryName + '</label>').appendTo(toParent);
                        });
                    } else {
                        toParent.html("没有数据");
                    }
                },
                error: function (data) {
                    SystemDialog.queryAlert(" lego 直播标签获取失败,请联系lego相关人员");
                    toParent.html("数据加载中失败");
                }
            }

            return {
                regName: Program.memo.getLegoCategory,
                options: option
            }
        }


        function getTargetName(param_id) {
            return {
                regName: Program.memo.targetName,
                options: {
                    type: "post",
                    url: Program.urlConfig.programList,
                    dataType: "json",
                    data: {"id": param_id, "deleteStatus": ""}
                }
            }
        }


        function initComplete() {
            $('div[name=multiAddDiv]').addndel({
                rowClass: 'control-group'
            })
            $('div[name=multiAddMoreStarDiv]').addndel({
                rowClass: 'control-group',
                addDecorator: function ($newRow, $clickedRow) {
                    $newRow.find('input[name=daojuStar]').bind({
                        input: function () {
                            var $textArea = $newRow.find('input[name=daojuStar]');
                            var textValue = $textArea.val();
                            var length = Com.string.getStrLength(textValue);
                            if (length > 5 * 2) {
                                $textArea.val(Com.string.substrCn(textValue, 5));
                            }
                        },
                        propertychange: function () {
                            var $textArea = $newRow.find('input[name=daojuStar]');
                            var textValue = $textArea.val();
                            var length = Com.string.getStrLength(textValue);
                            if (length > 5 * 2) {
                                $textArea.val(Com.string.substrCn(textValue, 5));
                            }
                        },
                        keyup: function () {
                            var $textArea = $newRow.find('input[name=daojuStar]');
                            var textValue = $textArea.val();
                            var length = Com.string.getStrLength(textValue);
                            if (length > 5 * 2) {
                                $textArea.val(Com.string.substrCn(textValue, 5));
                            }
                        }
                    }).trigger("keyup");

                    $newRow.find(".form-must").remove();
                    var count = parseInt($("input[name=daojuStarCount]").val()) + 1;
                    $("input[name=daojuStarCount]").val(count);
                    if (count <= 100) {
                        return true;
                    } else {
                        return false;
                    }
                },
                delDecorator: function ($deletedRow) {
                    var $must = $deletedRow.find(".form-must");
                    if ($must.length > 0) {
                        $deletedRow.next().find(".control-label").append($must);
                    }
                    var count = parseInt($("input[name=daojuStarCount]").val()) - 1;
                    $("input[name=daojuStarCount]").val(count);
                    return true;
                }
            })
            $("button[type=submit]").removeAttr("disabled");
            Program.View.initDialog();
            Program.View.fillForm();
            Program.View.initEditPicZone();
            Program.Suggest.initSuggest();
            Program.Suggest.bindSuggestData();
            Program.View.initRelationDataArea();
            Program.EventManager.bindEvent();
            Program.EventManager.bindValidate();
        }

        function unbindSport(selectedItem) {
            $.ajax({
                url: Program.urlConfig.unbindSportUrl,
                type: "post",
                data: {programQipuId: selectedItem.associatedLive.qipuId, matchId: selectedItem.id},
                dataType: "json",
                beforeSend: function (request) {
                    request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                },
                success: function (data) {
                    if (data != null && data.code == "A00000") {
                        $("#relationSportId").suggest("setValue", {id: selectedItem.id, label: selectedItem.matchName})
                        $("#relationSportId").attr("bind-data-id", selectedItem.id);
                        $("#relationSportId").attr("bind-data-title", selectedItem.label);
                        $("#relationSportId").attr("bind-data-matchStartTime", selectedItem.matchStartTime);
                    } else {
                        showTips({content: data.msg, type: "error"});
                    }
                },
                error: function (data) {
                    showTips({content: "not such data", type: "error"});
                }
            })
        }

        return {
            getChannel: getChannel,
            getLegoChannelType: getLegoChannelType,
            getLiveProgramType: getLiveProgramType,
            getLegoCategory: getLegoCategory,
            getTargetName: getTargetName,
            getLiveTmpOtherType: getLiveTmpOtherType,
            getGradeType: getGradeType,
            initComplete: initComplete,
            sendTask: sendTask,
            unbindSport: unbindSport
        }
    })();

    Program.Suggest = (function () {
        var qitanSuggest = {id: "qitanId", options: {
            source: Program.urlConfig.redirect,
            parseValue: function () {
                var val = this.element.val(),
                    ret = []
                return ret;
            },
            multiple: false,
            select: function (event, object) {
                this.value = object.item.id + "";
                return false;
            },

            process: function (json) {
                var ret = [],
                    self = this,
                    options = self.options,
                    itemData = null;
                var data = null;
                if (json == null) {
                    return [];
                }
                if (json.code === "A00000") {
                    data = $.isArray(json) ? json : json.data;
                }
                if (!data || !data.ids) {
                    return [];
                }
                $.map(data.ids, function (item) {
                    itemData = {};
                    itemData[options.valueKey] = item["resourceId"];
                    itemData[options.labelKey] = item["name"];
                    itemData["addDate"] = item["addDate"];

                    ret.push(itemData);
                });
                return ret;
            },
            method: "post",
            getParam: function (owner, term) {
                var requestData = {url: Program.Constant.thirdUrl_qitan_url, type: "get", params: {name: this.element.val(), resource_type: 1, page_size: 10}};
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },

            template: function (item) {
                var formatArr = [];
                formatArr.push('<span class="contract-width80">' + item["id"] + '</span>');
                formatArr.push('<span class="contract-width250">' + item["label"] + '</span>');
                formatArr.push('<span class="contract-width80">' + item["addDate"] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },

            header: '<div class="contract-item"><span class="contract-width80">评论ID</span><span class="contract-width250">评论名称</span><span class="contract-width80">创建时间</span></div>'
        }}
        var actorSuggest = {id: "ajaxSuggest", options: {
            source: Program.urlConfig.redirect,
            parseValue: function () {
                var self = this;
                var val = this.element.val(),
                    ret = [],
                    items = null,
                    itemData = null,
                    options = self.options;

                if (val) {
                    items = val.split(';');
                    $.each(
                        items, function (i, item) {
                            item = item.split(',');
                            itemData = {};
                            itemData[options.labelKey] = item[1];
                            itemData[options.valueKey] = item[0];
                            ret.push(itemData);
                        }
                    );
                }
                this._value('');
                return ret;
            },
            overDataLength: function (items) {
                var limit = auth.dev() ? 2 : 100;
                if (items.length == limit) {
                    showTips({content: "最多添加" + limit + "个人物", type: "error"});
                    return true;
                }
                return false;
            },
            process: function (json) {
                var ret = [],
                    self = this,
                    options = self.options,
                    itemData = null;
                var data = null;
                if (json == null) {
                    return [];
                }
                if (json.code === "A00000") {
                    data = $.isArray(json) ? json : json.data;
                }
                if (!data) {
                    return [];
                }
                $.map(data, function (item) {
                    itemData = {};
                    itemData[options.valueKey] = item["qipuId"];
                    itemData[options.labelKey] = item["properName"];
                    itemData["typeName"] = item["typeName"]
                    itemData["showId"] = item["id"];
                    itemData["gender"] = item.gender == null ? "" : item.gender == 0 ? "男" : "女";
                    itemData["auditStatus"] = item["auditStatus"] == 1 ? "审核通过" : "未审核";
                    itemData["careerName"] = item["careerName"];
                    ret.push(itemData);
                });
                return ret;
            },
            method: "post",
            getParam: function (owner, term) {
                var requestData = {url: Program.Constant.thirdUrl_audit_people, type: "get", params: {word: this.element.val(), valid: true}};
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },

            template: function (item) {
                var formatArr = [];
                formatArr.push('<span class="contract-width100">' + item.showId + '</span>');
                formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                formatArr.push('<span class="contract-width150">' + item["careerName"] + '</span>');
                formatArr.push('<span class="contract-width50">' + item.gender + '</span>');
                formatArr.push('<span class="contract-width150">' + item.typeName + '</span>');
                formatArr.push('<span class="contract-width150">' + item.auditStatus + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            header: '<div class="contract-item" >' +
                '<span class="contract-width100"> 人物ID</span>' +
                '<span class="contract-width150">名称</span>' +
                '<span class="contract-width150">别名</span>' +
                '<span class="contract-width50">性别</span>' +
                '<span class="contract-width150">人物类型</span>' +
                '<span class="contract-width150">审核状态</span></div>'
        }};

        var playbackSuggest = {
            id: "playbackSuggest",
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                autoFilter:false,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                select: function (event, object) {
                    //   this.value = object.item.id + "";
                    //  return false;
                    $("label[name=playbackHint]").html("ID:" + object.item.id);
                    return true;
                },
                getParam: function (term) {
                    var requestData = {url: Program.Constant.thirdUrl_video_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },

                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    $("label[name=playbackHint]").html("");
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }


                    var checkPurchase = function (val) {
                        var free = $('input:radio[name=freeStatus]:checked').val() == 1 ? true : false;
                        if (free) {
                            if (val == "1" || val == "2" || val == "3") {
                                return false;
                            }
                        } else {
                            if (val == "1" || val == "2" || val == "3") {
                                return true;
                            }
                            return false;
                        }
                        return true;
                    };

                    $.map(data, function (item) {
                        if (item["qipuId"] == null || item["qipuId"] == 0) {
                            return true;
                        }

                        if (!checkPurchase(item['isPurchase'])) {
                            return true;
                        }

                        itemData = {};
                        itemData[options.valueKey] = item["qipuId"];
                        itemData[options.labelKey] = item["properTitle"];
                        itemData[self._displayKey] = item["qipuId"];
                        itemData["channelName"] = item["channelName"];
                        itemData["globalPublishDate"] = item["globalPublishDate"];
                        itemData["isPurchase"] = item["isPurchase"];
                        itemData["pagePublishStatus"] = item["pagePublishStatus"];
                        ret.push(itemData);
                    });
                    return ret;
                },

                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
                    formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                    formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
                    formatArr.push('<span class="contract-width120">' + item.globalPublishDate + '</span>');
                    formatArr.push('<span class="contract-width80">' + Program.Formatter.purchase(item.isPurchase) + '</span>');
                    formatArr.push('<span class="contract-width80">' + Program.Formatter.publishStatus(item.pagePublishStatus) + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: '<div class="contract-item" >' +
                    '<span class="contract-width100">节目Id</span>' +
                    '<span class="contract-width150">节目显示名称</span>' +
                    '<span class="contract-width60">频道</span>' +
                    '<span class="contract-width120">发行时间</span>' +
                    '<span class="contract-width80">是否付费</span>' +
                    '<span class="contract-width80">发布状态</span></div>'
            }
        };

        var defaultHeaderHtml = '<div class="contract-item" >' +
            '<span class="contract-width100">奇谱ID</span>' +
            '<span class="contract-width150">显示名称</span>' +
            '<span class="contract-width60">频道</span>' +
            '<span class="contract-width120">版权到期时间</span>' +
            '<span class="contract-width80">是否付费</span>' +
            '<span class="contract-width80">发布状态</span></div>';

        var videoSuggest = {
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                parseValue: function () {
                    var self = this;
                    var val = this.element.val(),
                        ret = [],
                        items = null,
                        itemData = null,
                        options = self.options;

                    if (val) {
                        items = val.split(';');
                        $.each(
                            items, function (i, item) {
                                item = item.split(',');
                                itemData = {};
                                itemData[self._showKey] = item[0];
                                itemData[options.labelKey] = item[1];
                                itemData[options.valueKey] = item[0];
                                ret.push(itemData);
                            }
                        );
                    }
                    this._value('');
                    return ret;
                },

                getParam: function (term) {
                    var requestData = {url: Program.Constant.thirdUrl_video_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    $.map(data, function (item) {
                        if (item["qipuId"] == null || item["qipuId"] == 0) {
                            return true;
                        }
                        itemData = {};
                        itemData[options.valueKey] = item["qipuId"];
                        itemData[options.labelKey] = item["properTitle"];
                        itemData[self._showKey] = item["qipuId"];
                        itemData["channelName"] = item["channelName"];
                        itemData["copyrightEndTime"] = item["copyrightEndTime"] ? item["copyrightEndTime"] : null;
                        itemData["isPurchase"] = item["isPurchase"];
                        itemData["pagePublishStatus"] = item["pagePublishStatus"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    return Program.Formatter.getTemplate(item)
                },
                header: defaultHeaderHtml
            }
        }

        var albumSuggest = {
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                select: function (event, object) {
                    this.value = object.item.id + "";
                    return false;
                },
                getParam: function (term) {
                    var requestData = {url: Program.Constant.thirdUrl_album_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    $.map(data, function (item) {
                        if (item["qipuId"] == null || item["qipuId"] == 0) {
                            return true;
                        }
                        itemData = {};
                        itemData[options.valueKey] = item["qipuId"];
                        itemData[options.labelKey] = item["properTitle"];
                        itemData["channelName"] = item["channelName"];
                        itemData["copyrightEndTime"] = item["copyright"] ? item["copyright"][0].copyrightEndTime : null;
                        itemData["isPurchase"] = item["isPurchase"];
                        itemData["pagePublishStatus"] = item["pagePublishStatus"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    return Program.Formatter.getTemplate(item)
                },
                header: defaultHeaderHtml
            }
        }
        var playListSuggest = {
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },

                select: function (event, object) {
                    this.value = object.item.id + "";
                    return false;
                },

                getParam: function (term) {
                    var requestData = {url: Program.Constant.thirdUrl_playlist_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    $.map(data, function (item) {
                        if (item["qipuId"] == null || item["qipuId"] == 0) {
                            return true;
                        }
                        itemData = {};
                        itemData[options.valueKey] = item["qipuId"];
                        itemData[options.labelKey] = item["name"];
                        itemData["channelName"] = item["channelName"];
                        itemData["copyrightEndTime"] = "";
                        itemData["isPurchase"] = "";
                        itemData["pagePublishStatus"] = item["pagePublishStatus"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    return Program.Formatter.getTemplate(item)
                },
                header: defaultHeaderHtml
            }
        }

        var puyuSuggest = {
            id: "suggest_barCode",
            options: {
                source: Program.urlConfig.queryPuYu,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                ignoreWord: true,
                multiple: false,
                select: function (event, object) {
                    var flag = Program.View.fillPuYuOnClick(object.item);
                    if (flag == true) {
                        $("input[name=puyu_barCode]").val(object.item.value);
                        $("input[name=suggest_barCode]").val(object.item.value);
                    }
                    return false;
                },

                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null || json.code != "A00000") {
                        return [];
                    }
                    data = JSON.parse(json.data);
                    $.map(data.cprContents, function (item) {
                        itemData = {};
                        itemData[options.valueKey] = item["contractId"];
                        itemData[options.labelKey] = $("input[name=suggest_barCode]").val();
                        itemData["contractNumber"] = item["contractNumber"];
                        itemData["videoName"] = item["videoName"];
                        itemData["cprName"] = item["cprName"];
                        itemData["startTime"] = item["startTime"];
                        itemData["endTime"] = item["endTime"];
                        itemData["produceName"] = item["produceName"] || "";
                        itemData["produceTime"] = item["produceTime"] || "";
                        itemData["actors"] = item["actors"] || "";
                        itemData["directors"] = item["directors"] || "";
                        ret.push(itemData);
                    });
                    return ret;
                },
                method: "post",
                getParam: function (term) {
                    return { "barCode": term };
                },

                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["label"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + item["videoName"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + item["produceName"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + item["produceTime"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + item["actors"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + item["directors"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + item["cprName"] + '</span>');
                    formatArr.push('<span class="contract-width100" style="word-break:break-all">' + item["contractNumber"] + '</span>');
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["startTime"] + "~" + item["endTime"] + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },

                header: '<div class="contract-item">' +
                    '<span class="contract-width200">条形码</span>' +
                    '<span class="contract-width120">片名</span>' +
                    '<span class="contract-width120">出品方</span>' +
                    '<span class="contract-width120">发行时间</span>' +
                    '<span class="contract-width120">主演 /演唱者</span>' +
                    '<span class="contract-width120">导演</span>' +
                    '<span class="contract-width120">版权方</span>' +
                    '<span class="contract-width100">合同编号</span>' +
                    '<span class="contract-width200">授权起止时间</span>' +
                    '</div>'
//条形码 ，片名 出品方 发行时间 主演 /演唱者 导演 版权方 合同编号
            }
        }

        var vote_inner_url = "http://vote.i.iqiyi.com/eagle/runman/query_votes";
        var vote_token = "qiyi-vote-api-token-howareyou-fine3q";
        var defaultVoteHeaderHtml = '<div class="contract-item" >' +
            '<span class="contract-width150">投票ID</span>' +
            '<span class="contract-width200">投票名称</span>' +
//            '<span class="contract-width60">创建人</span>' +
            '<span class="contract-width150">创建时间</span>' +
            '</div>';
        var votePKSuggest = {
            id: "votePK",
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                select: function (event, object) {
                    this.value = object.item.id + "";
                    return false;
                },
                getParam: function (term) {
                    var requestData = {url: vote_inner_url, type: "get", params: {title: term, source: 6}};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    $.map(data, function (item) {
                        itemData = {};
                        itemData[options.valueKey] = item["voteid"];
                        itemData[options.labelKey] = item["mainTitle"];
                        itemData["createTime"] = item["createTime"] || 0;
                        if (itemData["createTime"] > 0) {
                            itemData["createTime"] = Program.Formatter.formatDate(new Date(itemData["createTime"]));
                        } else {
                            itemData["createTime"] = "";
                        }
                        itemData["title"] = item["mainTitle"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["id"] + '</span>');
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["title"] + '</span>');
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["createTime"] + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: defaultVoteHeaderHtml
            }
        }
        var voteRankSuggest = {
            id: "voteRank",
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                select: function (event, object) {
                    this.value = object.item.id + "";
                    return false;
                },
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                getParam: function (term) {
                    var requestData = {url: vote_inner_url, type: "get", params: {title: term, source: 7}};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    $.map(data, function (item) {
                        itemData = {};
                        itemData[options.valueKey] = item["voteid"];
                        itemData[options.labelKey] = item["mainTitle"];
                        itemData["createTime"] = item["createTime"] || 0;
                        if (itemData["createTime"] > 0) {
                            itemData["createTime"] = Program.Formatter.formatDate(new Date(itemData["createTime"]));
                        } else {
                            itemData["createTime"] = "";
                        }
                        itemData["title"] = item["mainTitle"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["id"] + '</span>');
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["title"] + '</span>');
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["createTime"] + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: defaultVoteHeaderHtml
            }
        }

        //var daoju_inner_url = "http://admin.vienx.qiyi.domain/api/partner/query.json";
        var daoju_inner_url = "http://" + (auth.dev() ? "10.153.133.118:8080" : "admin.vienx.qiyi.domain" ) + "/api/partner/query.json";
        var daoju_secret = auth.dev() ? '123456798' : 'LZl$UX*7bb^TTTdH$33R';
        var daoju_ip = auth.dev() ? '127.0.0.1' : '10.153.108.204';
        var defaultDaojuHeaderHtml = '<div class="contract-item" >' +
            '<span class="contract-width150">道具渠道号</span>' +
            '<span class="contract-width200">道具渠道名称</span>' +
            '<span class="contract-width150">创建时间</span>' +
            '<span class="contract-width150">创建人</span>' +
            '</div>';

        function createSign(obj) {
            var str = '';
            $.each(obj, function (k) {
                str += k + obj[k];
            });
            str += daoju_secret;
            console.log(str);
            return hex_sha1(utf16to8(str));
        };

        function utf16to8(str) {
            var out, i, len, c;

            out = "";
            len = str.length;
            for (i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                }
            }
            return out;
        }

        function hex_sha1(str) {
            var hexcase = 0;
            var chrsz = 8;


            function dosha1(s) {
                return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
            }

            function binb2hex(binarray) {
                var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
                var str = "";
                for (var i = 0; i < binarray.length * 4; i++) {
                    str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
                }
                return str;
            }

            function core_sha1(x, len) {
                x[len >> 5] |= 0x80 << (24 - len % 32);
                x[((len + 64 >> 9) << 4) + 15] = len;

                var w = Array(80);
                var a = 1732584193;
                var b = -271733879;
                var c = -1732584194;
                var d = 271733878;
                var e = -1009589776;

                for (var i = 0; i < x.length; i += 16) {
                    var olda = a;
                    var oldb = b;
                    var oldc = c;
                    var oldd = d;
                    var olde = e;

                    for (var j = 0; j < 80; j++) {
                        if (j < 16) w[j] = x[i + j];
                        else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                        var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
                        e = d;
                        d = c;
                        c = rol(b, 30);
                        b = a;
                        a = t;
                    }

                    a = safe_add(a, olda);
                    b = safe_add(b, oldb);
                    c = safe_add(c, oldc);
                    d = safe_add(d, oldd);
                    e = safe_add(e, olde);
                }
                return Array(a, b, c, d, e);

            }

            function sha1_ft(t, b, c, d) {
                if (t < 20) return (b & c) | ((~b) & d);
                if (t < 40) return b ^ c ^ d;
                if (t < 60) return (b & c) | (b & d) | (c & d);
                return b ^ c ^ d;
            }

            function sha1_kt(t) {
                return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
            }

            function safe_add(x, y) {
                var lsw = (x & 0xFFFF) + (y & 0xFFFF);
                var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
                return (msw << 16) | (lsw & 0xFFFF);
            }

            function rol(num, cnt) {
                return (num << cnt) | (num >>> (32 - cnt));
            }

            function str2binb(str) {
                var bin = Array();
                var mask = (1 << chrsz) - 1;
                for (var i = 0; i < str.length * chrsz; i += chrsz)
                    bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
                return bin;
            }

            return dosha1(str);
        }

        var daojuSuggest = {
            id: "daojuId",
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                select: function (event, object) {
                    this.value = object.item.label + "";
                    $('#daojuTip').html("渠道号: " + object.item.id);
                    return false;
                },
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                getParam: function (term) {
                    var params = {
                        api_key: 'epg',
                        format: 'json',
                        ip: daoju_ip,
                        partner_name: term,
                        time: Math.round(new Date().getTime() / 1000),
                        //time: 1459163882,
                        version: '1.0.0'
                    };

                    var paramSign = createSign(params);

                    params.sign = paramSign;

                    var requestData = {url: daoju_inner_url, type: "post",
                        params: params
                    };
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null,
                        count = 0;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }

                    $.map(data, function (item) {
                        itemData = {};
                        itemData[options.valueKey] = item["partner_code"];
                        itemData[options.labelKey] = item["partner_name"];
                        itemData["add_time"] = item["add_time"];
                        itemData["admin_username"] = item["admin_username"];

                        count += 1;
                        ret.push(itemData);
                    });
                    return ret.slice(0, 10);
                },
                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["id"] + '</span>');
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["label"] + '</span>');
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["add_time"] + '</span>');
                    formatArr.push('<span class="contract-width150" style="word-break:break-all">' + item["admin_username"] + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: defaultDaojuHeaderHtml
            }
        };


        var defaultSportHeaderHtml = '<div class="contract-item" >' +
            '<span class="contract-width200">赛程名称</span>' +
            '<span class="contract-width120">赛程开始时间</span>' +
            '<span class="contract-width120">赛程结束时间</span>' +
            '<span class="contract-width100">比赛阶段</span>' +
            '<span class="contract-width200">所属赛事</span>' +
            '<span class="contract-width120">是否绑定</span>' +
            '</div>';

        var sportSuggest = {
            id: "relationSportId",
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                select: function (event, object) {
                    var needQuery = false;
                    if (object.item.associatedLive != null && object.item.associatedLive != "") {
                        needQuery = Program.Dao.getProgram() == null || ( Program.Dao.getProgram() != null && object.item.associatedLive.qipuId != Program.Dao.getProgram().qipuId)
                    }
                    if (needQuery) {
                        this.value = "";
                        SystemDialog.queryConfirm("所选赛程已经绑定节目是否继续", function (flag) {
                            if (flag == true) {
                                Program.Task.unbindSport(object.item);
                            }
                        })
                        return false;
                    } else {
                        $("#relationSportId").attr("bind-data-id", object.item.id);
                        $("#relationSportId").attr("bind-data-title", object.item.label);
                        $("#relationSportId").attr("bind-data-matchStartTime", object.item.matchStartTime);
                        return true;
                    }
                },
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                getParam: function (term) {
                    var requestData = {url: Program.Constant.thirdUrl_sport_match_url, type: "get", params: {matchName: term, size: 10, order: "desc", orderBy: "matchName"}, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }

                    $.map(data, function (item) {
                        itemData = {};
                        itemData[options.valueKey] = item["matchQipuId"];
                        itemData[options.labelKey] = item["matchName"];
                        itemData["matchName"] = item["matchName"];
                        itemData["matchStartTime"] = item["matchStartTime"];
                        itemData["matchEndTime"] = item["matchEndTime"];
                        itemData["matchStartTime"] = item["matchStartTime"];
                        itemData["matchStage"] = item["matchStage"];
                        itemData["competitionName"] = item["competitionName"];
                        itemData["associatedLive"] = item["associatedLive"];
                        ret.push(itemData);
                    });
                    return ret;
                },
                // matchName s e matchStage competitionName
                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["matchName"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + Program.Formatter.transLongToDate(item["matchStartTime"]) + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + Program.Formatter.transLongToDate(item["matchEndTime"]) + '</span>');
                    formatArr.push('<span class="contract-width100" style="word-break:break-all">' + Program.Formatter.sportMatchStage(item["matchStage"]) + '</span>');
                    formatArr.push('<span class="contract-width200" style="word-break:break-all">' + item["competitionName"] + '</span>');
                    formatArr.push('<span class="contract-width120" style="word-break:break-all">' + Program.Formatter.associatedLive(item["associatedLive"]) + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: defaultSportHeaderHtml
            }
        }


        var defaultOAHeaderHtml = '<div class="contract-item" >' +
            '<span class="contract-width120">ID</span>' +
            '<span class="contract-width200">节目名称</span>' +
            '<span class="contract-width120">审核状态</span>' +
            '<span class="contract-width100">频道</span>' +
            '<span class="contract-width120">编辑</span>' +
            '</div>';

        var oa_test_url = "http://oa-trunktest.qiyi.domain/api/live/getLiveDetailsForEpg";
        //    var oa_test_url = "http://10.10.10.59:8081/qiyi_oa/api/live/getLiveDetailsForEpg";
        var oa_online_url = "http://home.qiyi.domain/api/live/getLiveDetailsForEpg";
        var oaSuggest = {
            id: "oaSuggest",
            options: {
                source: Program.urlConfig.redirect,
                method: "post",
                multiple: false,
                select: function (event, object) {
                    //   this.value = object.item.id + "";
                    //  return false;
                    // $("label[name=playbackHint]").html("ID:" + object.item.id);
                    $("#" + oaSuggest.id).data("suggestData", object.item)
                    Program.View.fillInitDataByOAData(object.item);
                    return true;
                },
                parseValue: function () {
                    var val = this.element.val(),
                        ret = []
                    return ret;
                },
                getParam: function (term) {
                    var requestData = {url: auth.dev() ? oa_test_url : oa_online_url, type: "post-raw", params: {queryParam: term, domainUser: auth.baseInfo.authInfo.email.replace("@qiyi.com", "")}, needCookie: true};
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "2000") {
                        data = json.message;
                    } else {
                        showTips({content: json.message, type: "error"});
                        return []
                    }
                    if (!data) {
                        return [];
                    }

                    $.map(data, function (item) {
                        itemData = {};
                        itemData[options.valueKey] = item["docNo"];
                        itemData[options.labelKey] = item["docNo"] + item["liveName"];
                        itemData["value"] = item["liveName"];
                        itemData["docNo"] = item["docNo"];
                        itemData["docStatus"] = item["docStatus"];
                        itemData["chiefEditorApprovalStatus"] = item["chiefEditorApprovalStatus"];
                        itemData["channel"] = item["channel"];
                        itemData["editorName"] = item["editorName"];
                        itemData["liveName"] = item["liveName"];
                        itemData["liveLevel"] = item["liveLevel"];
                        itemData["liveLevelABC"] = item["liveLevelABC"];
                        itemData["isVirBroadcastStation"] = item["isVirBroadcastStation"];
                        itemData["isChatRoom"] = item["isChatRoom"];
                        itemData["isProp"] = item["isProp"];
                        itemData["isManualCheck"] = item["isManualCheck"];
                        //    itemData["payType"] = item["payType"];
                        itemData["isCancelComment"] = item["isCancelComment"];
                        itemData["isShieldLogo"] = item["isShieldLogo"];
                        itemData["toDocDetailsUrl"] = item["toDocDetailsUrl"];
                        itemData["isPay"] = item["isPay"];
                        if (itemData.chiefEditorApprovalStatus == "checked" || itemData.chiefEditorApprovalStatus == "unchecked") {
                            ret.push(itemData);
                        }
                    });
                    return ret;
                },
                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width120">' + item["docNo"] + '</span>');
                    formatArr.push('<span class="contract-width200">' + item["liveName"] + '</span>');
                    formatArr.push('<span class="contract-width120">' + Program.Formatter.chiefEditorApprovalStatus(item["chiefEditorApprovalStatus"]) + '</span>');
                    formatArr.push('<span class="contract-width100">' + item["channel"] + '</span>');
                    formatArr.push('<span class="contract-width120">' + item["editorName"] + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: defaultOAHeaderHtml
            }
        }

        //var paopao_test_url = "http://sh.suggest.qiyi.domain";
        var paopao_oneline_url = "http://sh.suggest.qiyi.domain";
        var paopao_test_url = "http://10.153.111.60/apis/circle/getSuggestCircleByName.htm"
        var paopaoSuggest = {
            id: "paopaoSuggest",
            options: {
                source: Program.urlConfig.redirect,
                // source: (auth.dev() ? paopao_test_url : paopao_oneline_url ) + "/",
                select: function (event, object) {
                    //   this.value = object.item.id + "";
                    //     return false;
                    return false;
                },
                overDataLength: function (items) {
                    var limit = 20;
                    if (items.length == limit) {
                        showTips({content: "最多添加" + limit + "个圈子", type: "error"});
                        return true;
                    }
                    return false;
                },
                parseValue: function () {
                    var self = this;
                    var val = this.element.val(),
                        ret = [],
                        items = null,
                        itemData = null,
                        options = self.options;

                    if (val) {
                        items = val.split(';');
                        $.each(
                            items, function (i, item) {
                                item = item.split(',');
                                itemData = {};
                                itemData[options.labelKey] = item[1];
                                itemData[options.valueKey] = item[0];
                                ret.push(itemData);
                            }
                        );
                    }
                    this._value('');
                    return ret;
                },
                process: function (json) {
                    var ret = [],
                        self = this,
                        options = self.options,
                        itemData = null;
                    var data = null;
                    if (json == null) {
                        return [];
                    }
                    if (json.code === "A00000") {
                        data = $.isArray(json) ? json : json.data;
                    }
                    if (!data) {
                        return [];
                    }
                    if (auth.dev()) {
                        $.map(data, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["qipuId"];
                            itemData[options.labelKey] = item["name"];
                            ret.push(itemData);
                        });
                    } else {
                        $.map(data, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["entity_id"];
                            itemData[options.labelKey] = item["name"];
                            ret.push(itemData);
                        });
                    }
                    return ret;
                },
                method: "post",
                getParam: function (owner, term) {
                    var requestData = null;
                    if (auth.dev()) {
                        requestData = {url: paopao_test_url, type: "get", params: {circleName: this.element.val()}}
                    } else {
                        requestData = {url: paopao_oneline_url, type: "get", params: {if: "circle", key: encodeURIComponent(this.element.val()), ppuid: auth.baseInfo.authInfo.uid }};
                    }
                    return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                },

                template: function (item) {
                    var formatArr = [];
                    formatArr.push('<span class="contract-width100">' + item.id + '</span>');
                    formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                    return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                },
                header: '<div class="contract-item" >' +
                    '<span class="contract-width100"> 圈子ID</span>' +
                    '<span class="contract-width150">圈子名称</span>' +
                    '</div>'

            }
        }

        function initSuggest() {
            $("#" + qitanSuggest.id).suggest(qitanSuggest.options);
            $("#" + actorSuggest.id).suggest(actorSuggest.options);
            $("#" + playbackSuggest.id).suggest(playbackSuggest.options);
            $("input[name$=_simple-video]").suggest(videoSuggest.options);
            $("input[name$=_album]").suggest(albumSuggest.options);
            $("input[name$=_playlist]").suggest(playListSuggest.options);
            $("#" + puyuSuggest.id).suggest(puyuSuggest.options);
            $("#" + votePKSuggest.id).suggest(votePKSuggest.options);
            $("#" + voteRankSuggest.id).suggest(voteRankSuggest.options);
            $("#" + daojuSuggest.id).suggest(daojuSuggest.options);
            $("#" + sportSuggest.id).suggest(sportSuggest.options);

            $("#" + paopaoSuggest.id).suggest(paopaoSuggest.options);
            if (Program.Dao.getProgram() == null) {
                $("#" + oaSuggest.id).suggest(oaSuggest.options);
            }
        }

        function bindSuggestData() {
            var programEntity = Program.Dao.getProgram();
            if (programEntity != null && programEntity.matchSummary != null && programEntity.matchSummary.length > 0) {
                var jsonObj = JSON.parse(programEntity.matchSummary);
                var target = $("#" + sportSuggest.id);
                target.suggest("setValue", {id: jsonObj.id, label: jsonObj.title});
                target.attr("bind-data-id", jsonObj.id);
                target.attr("bind-data-title", jsonObj.title);
                target.attr("bind-data-matchStartTime", jsonObj.start);
            }
        }

        return {
            initSuggest: initSuggest,
            bindSuggestData: bindSuggestData
        }
    })();

    Program.EventManager = (function () {
        var checkTextArea = function (textArea, wordCount) {
            var $textArea = $(textArea);
            var textValue = $textArea.val();
            var length = Com.string.getStrLength(textValue);
            if (length > wordCount * 2) {
                $textArea.val(Com.string.substrCn(textValue, wordCount));
            }
            textValue = $textArea.val();
            length = Com.string.getStrLength(textValue);
            $textArea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
        }

        function editPic(flag) {
            if (flag) {
                $(".header button").hide();
                $(".results button").removeAttr("disabled");
                $(".operation").removeClass("disabled");
                $(".uploadButton").removeAttr("disabled");
                $(".button-manual").removeAttr("disabled");
                Program.memo.editPic = true;
            } else {
                $(".header button").show();
                $(".header button").removeAttr("disabled");
                $(".results button").prop("disabled", "disabled");
                $(".operation").addClass("disabled");
                $(".uploadButton").prop("disabled", "disabled");
                $(".button-manual").prop("disabled", "disabled");
                Program.memo.editPic = false;
            }
        }


        function queryForLvOne(params) {
            var requestData = {url: Program.Constant.thirdUrl_category_first_list_url, type: "get", params: params, needCookie: true};
            var option = {
                url: Program.urlConfig.redirect,
                type: "post",
                dataType: "json",
                data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                success: function (data) {
                    $("#secTagZone").html("");
                    if (data != null && data.data != null && data.data.channelData != null) {
                        queryForLvSec(data.data)
                    } else {
                        $("#secTagZone").html("没有数据");
                    }
                },
                error: function (data) {
                    $("#secTagZone").html("数据加载中失败");
                }
            }
            $.ajax(option)
        }

        function queryForLvSec(responseData) {
            var params = null;
            var requestData = null;
            Program.RemoteCheck.doCheck(responseData.channelData, function (data) {
                console.log("Program.RemoteCheck.doCheck queryForLvSec")
                $("input[name$=sec_category]").bind("click", function (event) {
                    var $sec_curTarget = $(event.currentTarget);
                    if ($sec_curTarget.prop("checked") == true) {
                        queryForLvThird({channelId: $sec_curTarget.attr("data-channel-id"), id: $sec_curTarget.val(), liveDisplay: 1, liveUsed: 1 })
                        console.log("wait to add $third_curTarget")
                    } else {
                        $("#thirdTagZone input[data-pid=" + $sec_curTarget.val() + "]").parent().remove();
                        console.log("wait to remove $third_curTarget");
                        updateThirdTagDiv();
                    }
                })
                var programEntity = Program.Dao.getProgram();
                if (programEntity != null && programEntity.category != null) {
                    var toParent = $("#secTagZone");
                    $.each(programEntity.categoryArr, function (i, element) {
                        if (element.level == 2) {
                            toParent.find("input[value=" + element.id + "]").click();
                        }
                    })
                }

            }, function startHandler(saveData) {

                $.each(saveData, function (i, element) {
                    params = {channelId: responseData.channelId, id: element.categoryId, liveDisplay: 1, liveUsed: 1 };
                    requestData = {url: Program.Constant.thirdUrl_category_child_list_url, type: "get", params: params, needCookie: true};
                    $.ajax({
                        url: Program.urlConfig.redirect,
                        type: "post",
                        dataType: "json",
                        data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                        success: function (data) {
                            element.complete = true;
                            if (data == null || data.length == 0) {
                                console.log("没有获得数据");
                                return;
                            }
                            if (data.length > 0) {
                                var toParent = $("#secTagZone");
                                $.each(data, function (i, element) {
                                    $('<label style="display: inline;margin-left: 5px"><input type="checkbox" data-channel-id="' + params.channelId + '" name="sec_category" data-name="' + element.name + '" value="' + element.id + '">' + element.name + '</label>').appendTo(toParent)
                                });
                            }
                        },
                        error: function (data) {
                            element.complete = true;
                            console.log("queryForLvSec error")
                        }
                    })

                });
            });
        }

        function updateThirdTagDiv() {
            var hasThirdCategory = $("input[name=third_category]");
            if (hasThirdCategory.length > 0) {
                $("#thirdTagDiv").show();
            } else {
                $("#thirdTagDiv").hide();
            }
        }

        function queryForLvThird(params) {
            console.log("Program.RemoteCheck.doCheck queryForLvThird")
            var requestData = {url: Program.Constant.thirdUrl_category_child_list_url, type: "get", params: params, needCookie: true};
            var programEntity = Program.Dao.getProgram();
            var options = {
                url: Program.urlConfig.redirect,
                type: "post",
                type: "post",
                dataType: "json",
                data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                success: function (data) {
                    if (data == null || data.length == 0) {
                        console.log("没有获得数据");
                    } else {
                        var htmlArr = [];
                        var toParent = $("#thirdTagZone");
                        $.each(data, function (i, element) {
                            $('<label style="display: inline;margin-left: 5px"><input type="checkbox" data-name="' + element.name + '" data-pid="' + element.pid + '" name="third_category" value="' + element.id + '">' + element.name + '</label>').appendTo(toParent);
                        });
                        if (programEntity != null && programEntity.category != null) {
                            $.each(programEntity.categoryArr, function (i, element) {
                                if (element.level == 3) {
                                    toParent.find("input[value=" + element.id + "]").prop("checked", true);
                                }
                            })
                        }
                    }
                    updateThirdTagDiv();
                },
                error: function (data) {
                    if (data == null) {
                        console.log("没有获得数据 error");
                        return;
                    }
                }
            }
            $.ajax(options);
        }

        function updateRecommendRateWithEpisodeGrade(val) {
            var recommendVal = 0;
            if (val == '') {
                recommendVal = 0;
            } else {
                recommendVal = 3 - parseInt(val) % 10 + 1;
            }
            $("select[name=recommendRate]").val(recommendVal);
        };

        function bindValidate() {
            var self = this;
            var channelEntity = Program.Dao.getChannel();
            if (channelEntity != null && channelEntity.liveType == 2) {
                $("input[name=passport_uid]").bind("focusout", function (event) {
                    var curTarget = $(event.currentTarget);
                    var $sec_curTarget = curTarget.val();
                    var helpblock = curTarget.parent().find("span.help-text");
                    doPassPortClean(helpblock, curTarget);
                    if (!/^[0-9]*$/.test($sec_curTarget)) {
                        doPassPortError(helpblock, curTarget, "请输入数字");
                        return
                    }
                    if ($.trim($sec_curTarget).length == 0) {
                        return;
                    } else {
                        var requestData = {url: Program.Constant.thirdUrl_passport_uid_url, type: "post", params: {uid: $sec_curTarget }, needCookie: true};
                        $.ajax({
                            url: Program.urlConfig.passportRequest,
                            type: "post",
                            dataType: "json",
                            data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                            success: function (data) {
                                if (data != null) {
                                    if ("A00000" == data.code) {
                                        doPassPortSuc(helpblock, data.data);
                                    } else {
                                        if (data.msg.indexOf("指定的uid不存在") != -1) {
                                            data.msg = "uid不存在,请重新输入";
                                        }
                                        doPassPortError(helpblock, curTarget, data.msg);
                                    }
                                } else {
                                    doPassPortError(helpblock, curTarget)
                                }
                            },
                            error: function (data) {
                                doPassPortError(helpblock, curTarget)
                            }
                        })
                    }
                });
                $("input[name=passport_nickname]").bind("focusout", function (event) {
                    var curTarget = $(event.currentTarget);
                    var $sec_curTarget = curTarget.val();
                    var helpblock = curTarget.parent().find("span.help-text");
                    doPassPortClean(helpblock, curTarget);
                    if ($.trim($sec_curTarget).length == 0) {
                        return;
                    } else {
                        var requestData = {url: Program.Constant.thirdUrl_passport_nk_url, type: "post", params: { nickname: $sec_curTarget }, needCookie: true};
                        $.ajax({
                            url: Program.urlConfig.passportRequest,
                            type: "post",
                            dataType: "json",
                            data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                            success: function (data) {
                                if (data != null) {
                                    if ("A00000" == data.code) {
                                        doPassPortSuc(helpblock, data.data);
                                        $("input[name=passport_nickname]").val(data.data.userinfo.nickname);
                                    } else {
                                        if (data.msg.indexOf("用户不存在") != -1) {
                                            data.msg = "昵称不存在,请重新输入";
                                        }
                                        doPassPortError(helpblock, curTarget, data.msg);
                                    }
                                } else {
                                    doPassPortError(helpblock, curTarget)
                                }
                            },
                            error: function (data) {
                                doPassPortError(helpblock, curTarget)
                            }
                        })
                    }
                })
            }
        }

        function doPassPortClean(helpblock, curTarget) {
            helpblock.html("");
            $("input[name=uid_hidden]").val("");
            $("input[name=nickname_hidden]").val("");
            $("#passport_div").removeClass("error");
            curTarget.removeClass("help-block");
        }

        function doPassPortSuc(helpblock, data) {
            helpblock.html("");
            $("input[name=uid_hidden]").val(data.userinfo.uid);
            $("input[name=nickname_hidden]").val(data.userinfo.nickname);
        }

        function doPassPortError(helpblock, curTarget, msg) {
            if (msg == null) {
                msg = "请求发生异常!"
            }
            helpblock.show();
            helpblock.html(msg);
            $("#passport_div").addClass("error");
            curTarget.addClass("help-block");
        }

        function bindEvent() {
            $("#qitanId").focusout(function () {
                var checkValue = $("#qitanId").val();
                var helpHint = $("span[for=qitanId]");
                var flag = Program.Validate.baseCheck({value: $("#qitanId").val(), error: "请输入整数", handler: function (msg) {
                    var helpHint = $("span[for=qitanId]");
                    helpHint.html("请输入整数");
                }, type: "number"})
                if (!flag) {
                    return;
                }
            })

            $("#category-a").click(function () {
                if ($('input[name="test"]:checked').val() == 0) {
                    Program.View.showCategoriesDlg();
                    Program.View._showHasSelectedCat();
                }
            });


            $("#categories-dlg").on('dblclick', '.parent_category', function () {

                if ($(this).val() > 0) {
                    var title = $(".parent_category").find("option:selected").text();
                    var id = $(".parent_category").val() + '_0';

                    var tmp = $("#category-val>span");

                    var seq = null;
                    $.each($(tmp), function () {

                        if ($(this).attr('data-tag-id') == id)
                            seq = true;

                    });

                    var tag_span = $('<span data-tag-id="' + id + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + title + '">' + title + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');

                    if (!seq)
                        $("#category-val").append(tag_span);

                }

            });

            // 大小分类事件绑定
            $("#categories-dlg").on('change', '.parent_category', function () {

                var pcObj = $(this);
                var parent_cate_id = $(this).val()[0];

                var sub_cate = $('.sub_category');
                var options = '';
                if (parent_cate_id > 0) {

                    var request = Program.Dao.genCategoriesRequestStr(parent_cate_id);

                    Program.Dao.getCategories({
                        request: request
                    }, function (json) {

                        sub_cate.empty();
                        $.each(json, function (i, item) {
                            options += '<option value="' + item.id + '">' + item.name + '</option>';
                        });
                        sub_cate.html(options);

                        sub_cate.unbind("dblclick").bind("dblclick", function () {
                            var tmp = $("#category-val>span");

                            if ($(this).val() > 0) {
                                var title = $(".parent_category").find("option:selected").text() + '_' + $(this).find("option:selected").text();
                                var id = $(".parent_category").val() + '_' + $(this).val();
                            } else {
                                var title = $(".parent_category option:selected").text();
                                var id = $(".parent_category").val() + '_' + 0;
                                ;
                            }

                            var seq = null;
                            $.each($(tmp), function () {

                                if ($(this).attr('data-tag-id') == id)
                                    seq = true;

                            });

                            var tag_span = $('<span data-tag-id="' + id + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + title + '">' + title + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');

                            if (!seq)
                                $("#category-val").append(tag_span);

                        });

                    });

                }
            });

            if (Program.memo.id > 0) {
                editPic(false);
                $(".header button").bind("click", function (event) {
                    editPic(true);
                });
            }
            //leftWordsCount
            $("#description").bind({
                input: function () {
                    checkTextArea(this, 200);
                },
                propertychange: function () {
                    checkTextArea(this, 200);
                },
                keyup: function () {
                    checkTextArea(this, 200);
                }
            }).trigger("keyup");

            $("#recommendRemark").bind({
                input: function () {
                    checkTextArea(this, 10);
                },
                propertychange: function () {
                    checkTextArea(this, 10);
                },
                keyup: function () {
                    checkTextArea(this, 10);
                }
            }).trigger("keyup");

            $("select[name$=SuggestType]").bind("change", function (event) {
                var $curTarget = $(event.currentTarget)
                var selectedValue = $curTarget.val();
                console.log("selectedValue")
                $curTarget.parent().find("span input").parent().hide();
                $curTarget.parent().find("span input[name$=_" + selectedValue + "]").parent().show();
            })
            $("select[name=frontSuggestType]").change();
            $("select[name=endSuggestType]").change();
            $("select[name$=SuggestType]").parent().find("span input").show();

            $("input[name=use_puyu_radio]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget)
                var puyuDiv = $("#puyuDiv");
                if ($curTarget.val() == 1) {
                    puyuDiv.show();
                } else {
                    puyuDiv.hide();
                    puyuDiv.find("input[type=text]").val("");
                }
            })

            $("input[name=public_level]").bind("click", function (event) {
                var programEntity = Program.Dao.getProgram();
                var $curTarget = $(event.currentTarget)
                if ($curTarget.val() == 5) {
                    $("input[name=test][value='1']").prop("checked", true);
                    $("input[name=test][value='1']").click();
                    $("input[name=test]").attr("disabled", "disabled");
                    if (programEntity != null && programEntity.id > 0) {
                        $("#visitLevel_detail").show();
                    }
                } else if ($curTarget.val() == 0) {
                    $("input[name=test]").removeAttr("disabled");
                    $("#visitLevel_detail").hide();
                }
            })
            $("input[name=test]").bind("click", function (event) {
                var categoryWarn = $('#category-warn');
                var tagshow = $('span.tagshow');
                var tag = $('input[name=tag]');
                var programEntity = Program.Dao.getProgram();
                if ($('input[name=test]:checked').val() == 1) {
                    tagshow.attr("record", tagshow.text());
                    tagshow.attr("recordTag", tag.val());
                    tagshow.text("正在直播_临时直播");
                    tag.val("200003919_200978719");
                    categoryWarn.css("display", "inline-block");
                    if (programEntity == null || (programEntity != null && programEntity.needOA == 1)) {
                        $("#oa_div").hide();
                    }
                } else {
                    tagshow.text(tagshow.attr("record"));
                    tag.val(tagshow.attr("recordTag"));
                    categoryWarn.css("display", "none");
                    if (programEntity == null || (programEntity != null && programEntity.needOA == 1)) {
                        $("#oa_div").show();
                    }
                }
            })
            //    $('input[name=test]:checked').click();

            $("input[name=public_level]:checked").click();
            $("select[name=channelCateTag]").bind("change", function (event) {
                $("#secTagDiv").show();
                $("#secTagZone").html("数据加载中....");
                $("#thirdTagDiv").hide();
                $("#thirdTagZone").html("");
                var $curTarget = $(event.currentTarget)
                var selectedValue = $curTarget.val();
                queryForLvOne({channel_id: parseInt(selectedValue), liveDisplay: 1, liveUsed: 1});
            });

            $("input[name=chat_enable]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget)
                var chatShowDiv = $("#chatShowDiv");
                var checkTypeDiv = $("#checkTypeDiv");
                var chatFakeDiv = $("#chatFakeDiv");
                var freeStatusInput = $("input[name=freeStatus]:checked");

                var chatRoomId = $("label[name=chatRoomId]");
                var daojuFlag = $("input[name=daojuFlag]");
                var chatRightsDiv = $("#chatRightsDiv");
                var chatPopupsDiv = $("#chatPopupsDiv");
                if ($curTarget.val() == 1) {
                    chatShowDiv.show();
                    chatRoomId.show();
                    checkTypeDiv.show();
                    if (freeStatusInput.val() == 0) {
                        chatRightsDiv.show();
                    }
                    chatFakeDiv.show();
                    chatPopupsDiv.show();
                    daojuFlag.removeAttr("disabled");

                } else {
                    chatShowDiv.hide();
                    chatRoomId.hide();
                    checkTypeDiv.hide();
                    chatRightsDiv.hide();
                    chatFakeDiv.hide();
                    chatPopupsDiv.hide();
                    $('input[name=chat_popups][value="0"]').prop("checked", true);
                    $('input[name=daojuFlag][value="0"]').prop("checked", true);
                    $("input[name=daojuFlag]:checked").click();
                    daojuFlag.attr("disabled", "disabled");

                    $('input[name=check_type][value="1"]').prop("checked", true);
                    $('input[name=check_type]:checked').click();
                }
                Program.View.opSetDisplayByRelation();
            });

            $("input[name=chat_enable]:checked").click();

            $("input[name=freeStatus]").bind("click", function (e) {
                var $curTarget = $(e.currentTarget)
                var html = '<option value="0">允许所有人发言</option>';
                if ($curTarget.val() == 0) {
                    html += '<option value="2">购买用户发言</option>';
                }

                $('select[name=chatRights]').html(html);

                if ($curTarget.val() == 1) {
                    $("#chatRightsDiv").hide();
                } else if ($("input[name=chat_enable]").val() == 1) {
                    $("#chatRightsDiv").show();
                }

                // set hint for playback
                var hint = {
                    'free': '*免费直播只能关联免费点播',
                    'paid': '*付费直播只能关联付费点播，关联后购买直(点)播自动享有点(直)播观看权益'
                };
                if ($curTarget.val() == 1) {
                    $('label[name=playbackHintPay]').text(hint.free);
                } else {
                    $('label[name=playbackHintPay]').text(hint.paid);
                }
            });

            var preValue = $('select[name=chatRights]').val();
            $("input[name=freeStatus]:checked").click();
            $('select[name=chatRights]').val(preValue);

            $("input[name=daojuFlag]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget)
                var daoju = $("#daoju");
                var daojuFlag = $("input[name=daojuFlag]");
                if ($curTarget.val() == 1) {
                    daoju.show();
                    if (!isFirstInit) {
                        $("#input_tab_list").val($("input[name=daojuStarFlag]:checked").val() == 0 ? "排行榜" : "明星榜");
                    }
                    var daojuId = $('#daojuId').data('id');
                    if (daojuId && daojuId !== '') {
                        $("input[name=daoju]").attr("disabled", "disabled");
                        $('#daojuTip').html("渠道号: " + daojuId);
                    }
                } else {
                    daoju.hide();
                }
                Program.View.opSetDisplayByRelation();
            });
            $("input[name=daojuFlag]:checked").click();

            $("input[name=daojuStarFlag]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget);
                var $addSingleStar = $("#addSingleStar");
                var $addMoreStar = $("#addMoreStar");
                var $tabListInput = $("#input_tab_list");
                var isNotFirstClick = false;
                if ($curTarget.val() == 0) {
                    $addSingleStar.show();
                    $addMoreStar.hide();
                } else {
                    $addSingleStar.hide();
                    $addMoreStar.show();
                }
                if (!isFirstInit) {
                    $tabListInput.val($curTarget.val() == 0 ? "排行榜" : "明星榜");
                }
            });
            $("input[name=daojuStarFlag]:checked").click();
            isFirstInit = false;


            //绑定导播台事件
            $("input[name=director_enable]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget);
                var $dbtRegionDiv = $("#directorRegion_div");

                if ($curTarget.val() == 0) { //关闭导播
                    $dbtRegionDiv.hide();
                } else {//开启导播
                    $dbtRegionDiv.show();
                }
            });
            $("input[name=director_enable]:checked").click();



            $('#daojuId').bind('input propertychange', function () {
                if ($(this).val().length == 0) {
                    $('#daojuTip').html("");
                }
            });

            $("input[name=snap_shot_type]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget);
                var $hint = $('#snap_shot_type_hint');
                var $gapDiv = $('#snapshot_gap_div');
                if ($curTarget.val() == 1) {
                    $hint.show();
                    $gapDiv.show();
                } else {
                    $hint.hide();
                    $gapDiv.hide();
                }
            });
            $("input[name=snap_shot_type]:checked").click();

            $("select[name=passport_select]").bind("change", function (event) {
                var $curTarget = $(event.currentTarget)
                var selectedValue = $curTarget.val();
                if (selectedValue == "option_uid") {
                    $("input[name=passport_nickname]").val("");
                    $("input[name=passport_nickname]").parent().find("span.help-text").html("");
                    $("#passport_uid_div").css("display", "inline")
                    $("#passport_nickname_div").hide();
                } else if (selectedValue == "option_nickname") {
                    $("input[name=passport_uid]").val("");
                    $("input[name=passport_uid]").parent().find("span.help-text").html("");
                    $("#passport_uid_div").hide();
                    $("#passport_nickname_div").css("display", "inline")
                }
            })

            $("select[name=project_type_select]").bind("change", function (event) {
                var $curTarget = $(event.currentTarget)
                var selectedValue = $curTarget.val();
                $("label[name=project_type_select_hint]").text("");
                if (selectedValue == "type_sale") {
                    $("input[name=hot][value='0']").prop("checked", true);
                    $("label[name=project_type_select_hint]").text("直播不显示广告");
                } else if (selectedValue == "type_nosale") {
                    $("input[name=hot][value='1']").prop("checked", true);
                    $("label[name=project_type_select_hint]").text("直播显示广告");
                }
            })
            //$("select[name=project_type_select]").change();


            var channelEntity = Program.Dao.getChannel();
            if (channelEntity != null && channelEntity.liveType == 2) {
                $("#channelCateTag").change();
                $("select[name=passport_select]").change();
            }

            $("select[name=episodeGrade]").bind("change", function (event) {
                var $curTarget = $(event.currentTarget);
                var selectedValue = $curTarget.val();
                updateRecommendRateWithEpisodeGrade(selectedValue);
            });

            $("#addSingleStar").find('input[name=daojuStar]').bind({
                input: function () {
                    checkTextArea(this, 8);
                    var val = this.value;
                    var $daojuReplaceStar = $('label[name=daojuReplaceStar]');
                    var label = $daojuReplaceStar.text();
                    $daojuReplaceStar.html("客户端显示我要支持" + val);
                },
                propertychange: function () {
                    checkTextArea(this, 8);
                },
                keyup: function () {
                    checkTextArea(this, 8);
                }
            }).trigger("keyup");

            $("#addMoreStar").find('input[name=daojuStar]').bind({
                input: function () {
                    checkTextArea(this, 5);
                },
                propertychange: function () {
                    checkTextArea(this, 5);
                },
                keyup: function () {
                    checkTextArea(this, 5);
                }
            }).trigger("keyup");
            $("#playbackSuggest").bind("keyup", function (event) {
                if ($(this).val().length == 0) {
                    $("label[name=playbackHint]").html("");
                }
            });

            $("input[name=waterMarkFlag]").bind("click", function (event) {
                var $curTarget = $(event.currentTarget)
                var $logoHiddenDiv = $("#logoHiddenDiv");
                if ($curTarget.val() == 1) {
                    $logoHiddenDiv.show();
                } else {
                    $logoHiddenDiv.hide();
                }
            });
            $("input[name=waterMarkFlag]:checked").click();
            // 分类对话框
            //绑定聊天室开关控制
            var isChatDisplay = $('input:radio[name=chat_display]:checked').val();
            $('input[name=radio_chat_room][value=' + isChatDisplay + ']').prop("checked", true);
            $("input[name=chat_display]").bind("click", function (event) {
                var curTarget = $(event.currentTarget)
                $('input[name=radio_chat_room][value=' + curTarget.val() + ']').prop("checked", true);
            })

        }

        function bindDateMax(name1, name2, plusData) {
            $("input[name=" + name1 + "]").datetimepicker({

                sliderAccessArgs: { touchonly: false },
                onClose: function (selectedDate) {
                    $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                    var toDate = new Date(selectedDate.replace(/-/g, "/"))
                    $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                }
            })
            if (plusData != null) {
                $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
            }
        }

        function bindDateMin(name1, name2, plusData) {
            $("input[name=" + name1 + "]").datetimepicker({

                sliderAccessArgs: { touchonly: false },
                onClose: function (selectedDate) {
                    $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                    var toDate = new Date(selectedDate.replace(/-/g, "/"))
                    $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                }
            })
            if (plusData != null) {
                $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
            }
        }

        return{
            bindEvent: bindEvent,
            bindValidate: bindValidate,
            bindDateMax: bindDateMax,
            bindDateMin: bindDateMin
        }
    })();
    Program.View = (function () {
        function fillPuYuField(puyuData) {
            if (puyuData == null) {
                return false;
            }
            try {
                var puyuJson = null;
                if (typeof(puyuData ) == "string") {
                    puyuJson = JSON.parse(puyuData);
                } else {
                    puyuJson = puyuData;
                }
                var dataArr = puyuJson.cprContents;
                var element = dataArr.length > 0 ? dataArr[0] : null;
                return fillPuYuOnClick(element);
            } catch (exception) {
                console.log(" exception " + exception);
                return false;
            }
        }

        function fillInitDataByOAData(oaData) {
            if (oaData.docNo == Program.memo.taiwan_oa) {
                console.log("taiwan oa special route ")
                return;
            }
            console.log("fillInitDataByOAData :" + JSON.stringify(oaData));
            if (oaData.chiefEditorApprovalStatus === "unchecked") {
                $("select[name=episodeGrade]").val("")
            } else {
                var episodeGradeValue = Program.Formatter.transToEpisodeGrade(oaData.liveLevel, oaData.liveLevelABC);
                $("select[name=episodeGrade]").val(episodeGradeValue);
                $("select[name=episodeGrade]").attr("disabled", true);
            }
            //节目名称
            $("input[name=pname]").val(oaData.liveName);
            //虚拟演播室
            $("input[name=director_enable][value=" + oaData.isVirBroadcastStation + "]").click();
            //人工审核
            $("input[name=check_type][value=" + (oaData.isManualCheck == 1 ? 2 : 1) + "]").click();
            //是否屏蔽logo
            $("input[name=waterMarkFlag][value=" + (oaData.isShieldLogo == 1 ? 0 : 1) + "]").click();
            //isCancelComment是否需要评论
            $("input[name=qitanMarkFlag][value=" + (oaData.isCancelComment == 1 ? 0 : 1) + "]").click();
            //启用道具
            $("input[name=daojuFlag][value=" + oaData.isProp + "]").click();
            //对应聊天室显示
            $("input[name=chat_display][value=" + oaData.isChatRoom + "]").click();
            //付费设置
            $("input[name=freeStatus][value=" + (oaData.isPay ? 0 : 1) + "]").click();
        }

        function fillPuYuOnClick(puyuData) {
            if (typeof(puyuData) == "string") {
                console.log("wait to do");
                return false;
            }
            var element = puyuData;
            if (!element.hasOwnProperty("contractNumber")
                || !element.hasOwnProperty("videoName")
                || !element.hasOwnProperty("startTime")
                || !element.hasOwnProperty("endTime")
                || !element.hasOwnProperty("cprName")
                ) {
                console.log("[fillPuYuOnClick] fail element :" + JSON.stringify(element))
                return false;
            }
            $("input[name=puyu_contractNumber]").val(element.contractNumber);
            $("input[name=puyu_videoName]").val(element.videoName);
            $("input[name=puyu_startTime]").val(element.startTime);
            $("input[name=puyu_endTime]").val(element.endTime)
            $("input[name=puyu_cprName]").val(element.cprName);
            return true;
        }

        function fillForm() {
            $("form[role=form]").submit(function () {
                return false;
            })

            $("#qitanId").val("");
            $("input[name=_simple-video]").val("");
            $("input[name=_album]").val("");
            $("input[name=_playlist]").val("");
            $("input[name=use_puyu_radio]").removeAttr("checked");
            $("input[name=bType]").removeAttr("checked");
            $("input[name=bType]").attr("disabled", "disabled");
            $("input[name=snap_shot_type][value='0']").prop("checked", true);
            $("input[name=use_puyu_radio]").removeAttr("checked");
            //默认为 娱乐
            $("#channelCateTag").val(7);
            $("#puyuShowDiv").hide();
            $("#passport_div").hide();
            $("#paopao_div").hide();
            $("#passport_nickname_div").hide();
            $("#passport_uid_div").hide();
            $("#directorEnable_div").hide();
            $("div.sportSuggestDiv").hide();
            $("#category-control-div").hide();
            $("div[name=freeStatus_div]").hide();
            initLiveProgramType();
            if (Program.memo.id > 0) {
                initByProgramData();
            } else {
                initByFatherData();
            }
            Program.EventManager.bindDateMin("streamStartPlayTime", "streamEndPlayTime");
            Program.EventManager.bindDateMax("streamEndPlayTime", "streamStartPlayTime");
            var element = Program.Dao.getChannel();
            if (element == null || element.allowPopups != 1) {
                $("input[name=dan_mu]").attr("disabled", "disabled")
                $("label[name=danmuHint]").css("display", "inline");
            }

            $("#danmu_div").hide();
            if (element != null && element.liveType == 2) {
                $("#passport_div").show();
                $("#channelCateTagDiv").show();
                $("#secTagDiv").show();
                $("#thirdTagDiv").show();
                $("#puyuShowDiv").show();
                $("#episodeGradeDiv").show();
                $("#liveTmpDiv").show();
                $("#projectDiv").show();
                $("#snapShotDiv").show();
                $("#resourceIdDiv").show();
                $("#ep_tag_div").show();
                $("#directorEnable_div").show();
                $("div.sportSuggestDiv").show();
                $("#category-control-div").show();
                $("div[name=freeStatus_div]").show();

                $("#paopao_div").show();
            }
        }


        function initByNull() {
            showTips({content: "not such data", type: "error"});
            Program.memo.id = 0;
            $("input[name=dan_mu]").attr("disabled", "disabled")
            $("form[role=form]").submit(function () {
                showTips({content: "非法数据", type: "error"});
                return false;
            })
        }

        function initLiveProgramType() {
            var channelEntity = Program.Dao.getChannel();
            if (channelEntity == null) {
                return
            }
            var result = Program.Dao.liveProgramType();
            var selectJDom = $("#type");
            var createDataArr = [];
            $.each(result.data, function (index, obj) {
                switch (channelEntity.liveType) {
                    case 1:
                        if (obj.key == 6) {
                            createDataArr.push(obj);
                        }
                        break;
                    case 2:
                        if (obj.key < 6) {
                            createDataArr.push(obj);
                        }
                        break;
                    case 3:
                        if (obj.key == 7) {
                            createDataArr.push(obj);
                        }
                        break;
                }
            });
            $.each(createDataArr, function (index, obj) {
                $("<option>", {
                    value: obj.key,
                    html: obj.descr
                }).appendTo(selectJDom);
            });
            selectJDom.bind("change", function (event) {
                if (event.currentTarget.value == 1) {
                    $("#sportContainer").show()
                } else {
                    $("#sportContainer").hide()
                }
            })
        }

        function fillProgramTag(programTag) {
            if (programTag != null && programTag.length > 0) {
                $('input[name=tag]').val(programTag);
                console.log("programTag" + programTag);
                var ids = [];
                var tags = programTag.split(",");
                for (var i = 0; i < tags.length; i++) {
                    ids.push(tags[i]);
                }
                Program.Dao.getParentCategories(ids, function (data) {
                    Program.Dao.getSubCategories(data, function () {
                        $('.tagshow').text(Program.Dao.subCategories.join(','));
                    });
                });
            }
        }

        function initByProgramData() {
            var programEntity = Program.Dao.getProgram();
            console.log("========"+JSON.stringify(programEntity));
            if (programEntity == null) {
                initByNull();
                return;
            }
            if (programEntity.category != null) {
                programEntity.categoryArr = JSON.parse(programEntity.category);
            }
            $("#oaSuggest").val(programEntity.oaDocNo);
            if (programEntity.needOA == 0 || programEntity.test == 1) {
                $("#oa_div").hide();
                if (programEntity.oaDocNo == Program.memo.defaultOA) {
                    $("#oaSuggest").attr("type", "password")
                }
            }
            $("#oaSuggest").attr("readonly", "readonly");
            if (programEntity.needOA == 1) {
                $("select[name=episodeGrade]").attr("disabled", "disabled");
            }

            Program.memo.fatherId = programEntity.fatherId;
            $("#fatherId").val(programEntity.fatherId);
            appendChannelList($("#fatherId").val());
            $("#visitLevel_detail").show();
            $("#endPlayTime").val(programEntity.endPlayTime);
            $("#endPlayTime").attr("readonly", "readonly");
            $("#carouselEpisode").val(programEntity.carouselEpisode);
            $("#startPlayTime").val(programEntity.startPlayTime);
            $("#startPlayTime").attr("readonly", "readonly");
            $("#streamStartPlayTime").val(programEntity.streamStartPlayTime || "");
            $("#streamEndPlayTime").val(programEntity.streamEndPlayTime || "");

            $("#qitanId").val(programEntity.qitanId);
            $("select[name=type]").val(programEntity.type);
            if (programEntity.episodeGrade > 0) {
                $("select[name=episodeGrade]").val(programEntity.episodeGrade);
            }
            if (programEntity.type != 1) {
                $("#sportContainer").hide();
            }
            $("#pname").val(programEntity.pname);
            $("input[name=weiboTopic]").val(programEntity.weiboTopic);
            $("input[name=leftChannel]").val(programEntity.leftChannel);
            $("input[name=audioChannel]").val(programEntity.audioChannel);
            $("input[name=rightChannel]").val(programEntity.rightChannel);

            $("select[name=recommendRate]").val(programEntity.recommendRate);
            $("select[name=project_type_select]").val(programEntity.projectType || "");
            if (programEntity.projectType == "type_sale") {
                $("label[name=project_type_select_hint]").text("直播不显示广告");
            } else if (programEntity.projectType == "type_nosale") {
                $("label[name=project_type_select_hint]").text("直播显示广告");
            }
            $("input[name=recommendRemark]").val(programEntity.recommendRemark || "");
            $("input[name=subjectUrl]").val(programEntity.subjectUrl || "");

            $("#description").val(programEntity.description);
            $("#logoUrl").val(programEntity.logoUrl);
            $("#input[name=orderLevel]").val(programEntity.orderBy);
            $("input[name=waterMarkFlag][value='" + programEntity.waterMarkFlag + "']").prop("checked", true);

            if (programEntity.logoHidden != null) {
                var logoHiddenJson = JSON.parse(programEntity.logoHidden);
                for (var v in logoHiddenJson) {
                    $("input[name=logoHidden][value='" + logoHiddenJson[v] + "']").prop("checked", true);
                }
            }
            $("input[name=subscribe][value='" + programEntity.subscribe + "']").prop("checked", true);
            $("input[name=dan_mu][value='" + programEntity.allowPopups + "']").prop("checked", true);
            $("input[name=qitanMarkFlag][value='" + programEntity.allowComment + "']").prop("checked", true);
            $("input[name=freeStatus][value='" + (programEntity.freeStatus ? 1 : 0) + "']").prop("checked", true);
            $("input[name=vipType][value='" + programEntity.vipType + "']").prop("checked", true);
            if (programEntity.freeStatus === 0) {
                $("input[name=vipType]").attr("disabled", "disabled");
            }
            $("input[name=qiyiProduct][value='" + (programEntity.qiyiProduct || 0) + "']").prop("checked", true);
            $("input[name=qiyiExclusive][value='" + (programEntity.qiyiExclusive || 0) + "']").prop("checked", true);
            console.log(programEntity.publicLevel);
            if (programEntity.publicLevel == null || programEntity.publicLevel < 0) {
                programEntity.publicLevel = 0;

            }
            $("input[name=director_enable][value='" + programEntity.directorEnable + "']").prop("checked", true);
            if (programEntity.directorEnable === 1) {
                $("input[name=director_enable]").prop("disabled", "disabled");
            }

            //设置dbt_region
            var dbtRegionVal = 0;
            if (programEntity.dbtRegion == "bj") {
                dbtRegionVal = 0;
            }else if(programEntity.dbtRegion == "sh"){
                dbtRegionVal = 1;

            }else if (programEntity.dbtRegion == "tw"){
                dbtRegionVal = 2;
            }else{
                dbtRegionVal = 0;
            }
            $("input[name=dbt_region][value='" + dbtRegionVal + "']").prop("checked", true);

            //是否正在导播
            if(programEntity.directorOpen === 1){
                $("input[name=dbt_region]").prop("disabled", "disabled");
                $("label[name=dbt_region_desc]").after($("<label class=\"radio inline\" style=\"color: red;\" name=\"dbt_region_desc\">（注：如需修改请先删除导播）</label>"));
            }

            $("input[name=public_level][value='" + programEntity.publicLevel + "']").prop("checked", true);
            $("input[name=chat_fake][value='" + programEntity.chatFake + "']").prop("checked", true)
            var submitButton = $("button[type=submit]");
            submitButton.bind("click", function () {
                console.log("ready to submit editData");
                Program.Service.submitHandler("edit");
                return false;
            });

            // init puyu relation start;
            $("#puyuDiv").hide();
            $("input[name=use_puyu_radio][value='0']").prop("checked", true);
            if (programEntity.barCode != null && programEntity.puyuData != null) {
                if (fillPuYuField(programEntity.puyuData)) {
                    $("input[name=puyu_barCode]").val(programEntity.barCode);
                    $("input[name=suggest_barCode]").val(programEntity.barCode);
                    $("input[name=use_puyu_radio][value='" + 1 + "']").prop("checked", true);
                    $("#puyuDiv").show();
                }
            }
            if (programEntity.chatRoomId > 0) {
                $("label[name=chatRoomId]").html("聊天室ID：" + programEntity.chatRoomId);
            }
            // init displayRecommend
            // console.log("displayRecommend: " + JSON.stringify(programEntity));
            $('input[name=is_dispaly_recommend][value=' + programEntity.displayRecommend + ']').prop("checked", true);

            $('input[name=chat_enable][value=' + programEntity.chatEnable + ']').prop("checked", true);
            $('input[name=chat_display][value=' + programEntity.chatDisplay + ']').prop("checked", true);


            //if (programEntity.chatRoomId > 0 && programEntity.chatEnable == 0) {
            //    $("input[name=chat_enable]").attr("disabled", "disabled");
            //    $("input[name=chat_display]").attr("disabled", "disabled");
            //}
            $('input[name=chat_popups][value=' + programEntity.chatPopups + ']').prop("checked", true);
            $('input[name=check_type][value=' + programEntity.checkType + ']').prop("checked", true);


            $('select[name=chatRights]').val(programEntity.chatRights);

            $('input[name=daojuFlag][value=' + programEntity.daojuEnable + ']').prop("checked", true);
            $('#daojuId').val(programEntity.daojuName);
            $('#daojuId').data("id", programEntity.daojuId);
            if (typeof programEntity.daojuId !== 'undefined' && programEntity.daojuId !== '') {
                $('#daojuTip').html("渠道号: " + programEntity.daojuId);
                $('#daojuId').attr("disabled", "disabled");
                var daojuStarJson = jQuery.parseJSON(programEntity.daojuStar);
                $('input[name=daojuStarFlag][value=' + daojuStarJson.daojuStarFlag + ']').prop("checked", true);
                if (daojuStarJson.starList.length > 0) {
                    if (daojuStarJson.daojuStarFlag == 0) {
                        var $addSingleStar = $("#addSingleStar");
                        $addSingleStar.find("input[name=daojuStar]").val(daojuStarJson.starList[0].show_name);
                        $addSingleStar.find("input[name=daojuStarId]").val(daojuStarJson.starList[0].id);
                        $addSingleStar.find("input[name=daojuStarImg]").val(daojuStarJson.starList[0].show_pic);
                        $('label[name=daojuReplaceStar]').html("客户端显示我要支持" + daojuStarJson.starList[0].show_name);
                    } else {
                        var $addMoreStar = $("#addMoreStar");
                        $.each(daojuStarJson.starList, function (index, target) {
                            var $addBtn = $addMoreStar.find("button[class='btn add blue-btn']");
                            $addBtn.parent().find("input[name=daojuStar]").val(target.show_name);
                            $addBtn.parent().find("input[name=daojuStarId]").val(target.id);
                            $addBtn.parent().find("input[name=daojuStarImg]").val(target.show_pic);
                            if (index < daojuStarJson.starList.length - 1) {
                                $addBtn.click();
                            }
                        });
                    }
                }
            }

            // init puyu relation end;

            var channelEntity = Program.Dao.getChannel();
            if (channelEntity == null) {
                return
            }
            if (channelEntity.liveType != 3) {
                $("#bTypeDiv").hide();
            } else {
                $("#bTypeDiv").show();
                $("input[name=bType][value=" + programEntity.live + "]").prop("checked", true);
            }

            if (channelEntity.liveType == 2) {
                if (programEntity.categoryArr != null && programEntity.categoryArr.length > 0) {
                    $.each(programEntity.categoryArr, function (i, element) {
                        if (element.dataMode == 1) {
                            $('input[name=ep_tag_label][value=' + element.id + ']').prop("checked", true);
                        } else if (element.level == 1) {
                            $("#channelCateTag").val(element.id);
                        }
                    })
                }
                fillProgramTag(programEntity.programTag)


                $("#endPlayTime").removeAttr("readonly");
                $("#startPlayTime").removeAttr("readonly");
                Program.EventManager.bindDateMin("startPlayTime", "endPlayTime", { maxDate: programEntity.endPlayTime, maxDateTime: new Date(programEntity.endPlayTime.replace(/-/g, "/"))});
                Program.EventManager.bindDateMax("endPlayTime", "startPlayTime", { minDate: programEntity.startPlayTime, minDateTime: new Date(programEntity.startPlayTime.replace(/-/g, "/"))});
                $("input[name=freeStatus]").prop("disabled", "disabled");
                $("#resourceId").val(programEntity.resourceId);
                $("input[name=snap_shot_type][value='" + programEntity.snapShotType + "']").prop("checked", true);
                if (programEntity.snapShotType == 1) {
                    $("input[name=snap_shot_type]").prop("disabled", "disabled");
                    $('select[name=snapshot_gap_select]').val(programEntity.snapShotGap < 0 ? 300 : programEntity.snapShotGap);
                }
                //http://www.iqiyi.com/l_19rt3rbgzr.html
                var keyPageUrl = programEntity.pageUrl.replace("http://www.iqiyi.com/l_", "").replace("\.html", "");
                var internal_url = "http://i.lequ.iqiyi.com/l_xxx.html".replace("xxx", keyPageUrl);
                var out_url = "http://www.iqiyi.com/inner_xxx.html".replace("xxx", keyPageUrl);
                $("span[name=weburl_internal]").html("<a href='" + internal_url + "'>" + internal_url + "</a>");
                $("span[name=weburl_out]").html("<a href='" + out_url + "'>" + out_url + "</a>");
            } else if (channelEntity.liveType == 1) {
                $("#pname").prop("disabled", "disabled");
                $("input[name=freeStatus][value='" + 1 + "']").prop("checked", true);
                $("input[name=freeStatus][value='" + 1 + "']").parent().parent().hide();
            } else if (channelEntity.liveType == 3) {
                $("input[name=carouselEpisode]").show();
                $("input[name=freeStatus]").prop("disabled", "disabled");
                if (new Date(programEntity.startPlayTime.replace(/-/g, "/")).getTime() - new Date().getTime() > 30 * 60 * 1000) {
                    $("#endPlayTime").removeAttr("readonly");
                    $("#startPlayTime").removeAttr("readonly");
                    Program.EventManager.bindDateMin("startPlayTime", "endPlayTime", { maxDate: programEntity.endPlayTime, maxDateTime: new Date(programEntity.endPlayTime.replace(/-/g, "/"))});
                    Program.EventManager.bindDateMax("endPlayTime", "startPlayTime", { minDate: programEntity.startPlayTime, minDateTime: new Date(programEntity.startPlayTime.replace(/-/g, "/"))});
                } else {
                    $("#startPlayTimeTip").html('该节目已结束，时间不允许修改');
                }
            }

            $('input[name=hot][value=' + programEntity.hot + ']').prop("checked", true);
            $('input[name=test][value=' + programEntity.test + ']').prop("checked", true);

            if (programEntity.test == 1 && channelEntity.liveType == 2) {
                $('#category-warn').css("display", "inline-block");
            }

            if (channelEntity.liveType != 2) {
                $("#hotDiv").hide();
                $("#testDiv").hide();
            }

            Program.View.initOperationTabControlArea(programEntity.tabControls);
        }

        function initByFatherData() {

            if (Program.memo.fatherId > 0) {
                $("#fatherId").val(Com.url.getParameter("fatherId"));
                appendChannelList($("#fatherId").val(), true);
            } else {
                appendChannelList();
            }
            $("button[type=submit]").bind("click", function () {
                console.log("ready to submit saveData")
                Program.Service.submitHandler("save");
                return false;
            });
            Program.EventManager.bindDateMin("startPlayTime", "endPlayTime");
            Program.EventManager.bindDateMax("endPlayTime", "startPlayTime");

            Program.View.initOperationTabControlArea(Program.Config.defaultOperationTabControl);
        }

        function initRelationDataArea() {
            if (Program.memo.id == 0) {
                return;
            }
            var programEntity = Program.Dao.getProgram();
            if (programEntity == null) {
                initByNull();
                return;
            }
            fillRelationData(programEntity.relationList);
        }

        function addSingleItem(dataArr, regName) {
            if (dataArr.length > 0) {
                if (!dataArr[0].label) {
                    dataArr[0].label = "" + dataArr[0].id;
                }
                $(regName).suggest("setValue", dataArr[0]);
            }
        }

        function addMultipleItem(dataArr, regName, showKey) {
            showKey = showKey ? true : false;
            $.each(dataArr, function (index, target) {
                if (showKey) {
                    target["$$autocompleteShowKey"] = target.id;
                }
                $(regName).suggest("addValue", target);
            })
        }

        function fillRelationData(relationEntityList) {
            var base1Arr = [];
            var base3Arr = [];
            var base4Arr = [];
            var base5Arr = [];
            var base6Arr = [];
            var base7Arr = [];
            var base106Arr = [];
            var base107Arr = [];
            var base401Arr = [];//关联圈子
            var passportData = {uid: "", nickname: ""};
            var itemModel = null;
            if (relationEntityList != null && relationEntityList.length > 0) {
                $.each(relationEntityList, function (index, element) {
                    itemModel = {};
                    itemModel.id = element.key;
                    itemModel.label = element.value;
                    switch (element.type) {
                        case 1:
                            base1Arr.push(itemModel);
                            break;
                        case 3:
                            base3Arr.push(itemModel);
                            break;
                        case 4:
                            base4Arr.push(itemModel);
                            break;
                        case 5:
                            base5Arr.push(itemModel);
                            break;
                        case 6:
                            base6Arr.push(itemModel);
                            break;
                        case 7:
                            base7Arr.push(itemModel);
                            break;
                        case 106:
                            base106Arr.push(itemModel);
                            break;
                        case 107:
                            base107Arr.push(itemModel);
                            break;
                        case 201:
                            $("select[name=live_temp_other]").val(element.value)
                            break;
                        case 301:
                            passportData.uid = element.value;
                            if (element.key == 1) {
                                passportData.key = "uid";
                            }
                            break;
                        case 302:
                            passportData.nickname = element.value;
                            if (element.key == 1) {
                                passportData.key = "nickname";
                            }
                            break;
                        case 401:
                            base401Arr.push(itemModel);
                            break;
                    }
                })
            }
            addMultipleItem(base1Arr, '#ajaxSuggest', false);
            addSingleItem(base7Arr, '#playbackSuggest');
            if (base7Arr.length > 0) {
                $("label[name=playbackHint]").html("ID:" + base7Arr[0].id);
            }

            addSingleItem(base106Arr, '#votePK');
            addSingleItem(base107Arr, '#voteRank');
            $.each(base3Arr, function (index, target) {
                var $addBtn = $("#addndelSample3").find("button[class='btn add blue-btn']");
                $addBtn.parent().find("input[name=base_3_team]").val(target.label);
                $addBtn.parent().find("input[name=base_3_score]").val(target.id);
                $addBtn.click()
            })
            var checkKey = -1;
            var idType = null;
            if (base5Arr.length > 0) {
                itemModel = base5Arr[0]
                idType = checkIdType(itemModel.id + "");
                if (idType != null) {
                    $("select[name=frontSuggestType]").val(idType);
                    if (idType == "simple-video") {
                        addMultipleItem(base5Arr, '#appendFront_' + idType, true);
                    } else {
                        addSingleItem(base5Arr, '#appendFront_' + idType);
                    }
                }
            }
            if (base6Arr.length > 0) {
                itemModel = base6Arr[0]
                idType = checkIdType(itemModel.id + "")
                if (idType != null) {
                    $("select[name=endSuggestType]").val(idType);
                    if (idType == "simple-video") {
                        addMultipleItem(base6Arr, '#appendEnd_' + idType, true);
                    } else {
                        addSingleItem(base6Arr, '#appendEnd_' + idType);
                    }
                }
            }

            // init passport id ;
            initPassportId(passportData);
            initPaoPaoData(base401Arr);

        }

        function initPassportId(passportData) {
            $("input[name=uid_hidden]").val(passportData.uid);
            $("input[name=nickname_hidden]").val(passportData.nickname);
            $("select[name=passport_select]").val("option_" + passportData.key);
            $("input[name=passport_" + passportData.key + "]").val(passportData[passportData.key]);
        }

        function initPaoPaoData(base401Arr) {
            var parent = $("#paopaoSuggest");
            $.each(base401Arr, function (index, target) {
                target.id = target.id * 100 + 47;
                parent.suggest("addValue", target);
            })
        }

        function checkIdType(idStr) {
            var endStr = idStr.substr(idStr.length - 2)
            switch (endStr) {
                case "00":
                    return "simple-video";
                case "01":
                    return "album";
                case "02":
                    return "playlist";
                default :
                    return null;
            }
        }

        function appendChannelList(fatherId, newProgram) {
            var element = Program.Dao.getChannel()
            if (element != null) {
                var selectJDom = $("#selectedChannelName");
                selectJDom.val(element.name);
                selectJDom.attr("readonly", "readonly");
                $("input[name=orderLevel]").val(element.orderBy);
                $('#qitanId').val(element.qitanId);
                $('#subjectUrlDiv').hide();
                if (element.liveType == 2) {
                    $('#subjectUrlDiv').show();
                    $("#visitLevelDiv").show();
                }
                $("input[name=subjectUrl]").val(element.subjectUrl || "");

            }
            if (newProgram) {
                $("#visitLevel_detail").hide();
                $("input[name=dan_mu][value='" + element.allowPopups + "']").prop("checked", true);
                $("input[name=qitanMarkFlag][value='" + element.shouldDisplay + "']").prop("checked", true);
            }
        }

        function initEditPicZone() {
            var responseData = null;
            var picEnity = null;
            if (Program.memo.id == 0) {
                if (Program.memo.fatherId > 0) {
                    picEnity = Program.Dao.getChannel();
                    if (picEnity != null && picEnity.liveType != 2) {
                        picEnity = null;
                    }
                }
            } else {
                picEnity = Program.Dao.getProgram();
            }
            if (picEnity == null || picEnity.logoUrl == null || picEnity.logoUrl == "") {
                return;
            }
            var demoData = {"imageDatas": JSON.parse(picEnity.logoUrl) };
            if (demoData.imageDatas.length == 0) {
                return;
            }
            var materials = [];
            $.each(demoData.imageDatas[0].materials, function (index, element) {
                materials.push({url: element.url, spath: element.location, id: element.id, data: { id: element.id }});
            })
            var elementValue = {};
            $.each(demoData.imageDatas[0].images, function (index, element) {
                var plusData = {};
                var position = element.editInfo.cutPosition.split(",");
                elementValue[element.editInfo.scale.replace(":", "-")] = plusData;
                plusData.x1 = parseInt(position[0]);
                plusData.x2 = parseInt(position[0]) + parseInt(position[3]);
                plusData.y1 = parseInt(position[1]);
                plusData.y2 = parseInt(position[1]) + parseInt(position[2]);
                plusData.spath = element.materialLocation;
                $.each(demoData.imageDatas[0].materials, function (index, originalImg) {
                    if (element.materialLocation == originalImg.location) {
                        plusData.imgsrc = originalImg.url;
                        return false;
                    }
                })
                plusData.data = {};
            })
            $("#AlbumEditScreenCorp").imagecrop("addImages", materials, function () {
                $("#AlbumEditScreenCorp").imagecrop("setValue", elementValue);
            });
        }

        function initDialog() {
            $("#oepn-item-dlg").dialog({
                title: "提示",
                autoOpen: false,
                width: 400,
                modal: true,
                dialogClass: 'alert',
                resizable: false
            })
            $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            $("button[name=con_created]").bind("click", function (event) {
                $("#oepn-item-dlg").dialog("close");
                Program.Service.submitHandler("save", true);
            })
            $("button[name=con_cancel]").bind("click", function (event) {
                $("#oepn-item-dlg").dialog("close");
            })
        }

        function initOperationTabControlArea(d) {
            var data = null;
            if (d === undefined || d == "") {
                data = JSON.parse(Program.Config.defaultOperationTabControl);
            } else {
                data = JSON.parse(d);
            }

            var area = $('#operationTabControlArea');

            content = [];

            $.each(data, function (i, e) {
                content.push(Program.View.makeUpTab(e));
            });

            area.html(content.join(""));

            area.find('li:first-child button.up').hide();
            area.find('li:last-child button.down').hide();

            Program.View.opSetDisplayByRelation();

            $.each(area.find('li'), function (i, e) {
                Program.View.opBindDefaultClick(e);
                Program.View.opBindDisplayClick(e);
                Program.View.opBindKeyupEvent(e);
            })
        }

        function opHideUpDownBtn() {
            var area = $('#operationTabControlArea');

            area.find('li:first-child button.up').hide();
            area.find('li:last-child button.down').hide();
        }

        function makeUpTab(e) {
            var htmlArr = [];
            switch (parseInt(e.type)) {
                case 0:
                    htmlArr.push('<li data-type="' + e.type + '"><div class="operationDiv"><div class="control-group">');
                    htmlArr.push('<select style="width:90px;" disabled="disabled"><option value="simple-video">聊天室</option></select>');
                    htmlArr.push('<input type="text" name="op_display_name" placeholder="" value="' + e.display_name + '" style="margin-left: 4px;">');
                    htmlArr.push('<label name="op_display_name_hint" style="color: #FF0000; display: none;">错误提示</label></div>');
                    htmlArr.push('<div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">是否显示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_chat_room" value="1"' + (e.is_enable == 1 ? "checked" : "") + ' disabled>是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_chat_room" value="0"' + (e.is_enable == 0 ? "checked" : "") + ' disabled>否</label>');
                    htmlArr.push('<label class="inline radio" style="color: #bfbfbf">聊天室开关控制</label>');
                    htmlArr.push('</div></div><div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">默认展示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_chat_room" value="1"' + (e.is_default == 1 ? "checked" : "") + ' >是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_chat_room" value="0"' + (e.is_default == 0 ? "checked" : "") + ' >否</label>');
                    htmlArr.push('<button type="button" class="btn add blue-btn down" onclick="Program.View.opTabMove(this, 1)"> 下移</button>');
                    htmlArr.push('<button type="button" class="btn add blue-btn up" onclick="Program.View.opTabMove(this, 0)"> 上移</button>');
                    htmlArr.push('</div></div></div></li>');
                    break;
                case 1:
                    htmlArr.push('<li data-type="' + e.type + '"><div class="operationDiv"><div class="control-group">');
                    htmlArr.push('<select style="width:90px;" disabled="disabled"><option value="simple-video">看更多</option></select>');
                    htmlArr.push('<input type="text" name="op_display_name" placeholder="" value="' + e.display_name + '" style="margin-left: 4px;">');
                    htmlArr.push('<label name="op_display_name_hint" style="color: #FF0000; display: none;">错误提示</label></div>');
                    htmlArr.push('<div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">是否显示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_more" value="1"' + (e.is_enable == 1 ? "checked" : "") + '>是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_more" value="0"' + (e.is_enable == 0 ? "checked" : "") + '>否</label>');
                    htmlArr.push('</div></div><div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">默认展示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_more" value="1"' + (e.is_default == 1 ? "checked" : "") + ' >是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_more" value="0"' + (e.is_default == 0 ? "checked" : "") + ' >否</label>');
                    htmlArr.push('<button type="button" class="btn add blue-btn down" onclick="Program.View.opTabMove(this, 1)"> 下移</button>');
                    htmlArr.push('<button type="button" class="btn add blue-btn up" onclick="Program.View.opTabMove(this, 0)"> 上移</button>');
                    htmlArr.push('</div></div></div></li>');
                    break;
                case 2:
                    htmlArr.push('<li data-type="' + e.type + '"><div class="operationDiv"><div class="control-group">');
                    htmlArr.push('<select style="width:90px;" disabled="disabled"><option value="simple-video">排行榜</option></select>');
                    htmlArr.push('<input type="text" name="op_display_name" placeholder="" value="' + e.display_name + '" style="margin-left: 4px;" id="input_tab_list">');
                    htmlArr.push('<label name="op_display_name_hint" style="color: #FF0000; display: none;">错误提示</label></div>');
                    htmlArr.push('<div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">是否显示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_list" value="1"' + (e.is_enable == 1 ? "checked" : "") + ' disabled>是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_list" value="0"' + (e.is_enable == 0 ? "checked" : "") + ' disabled>否</label>');
                    htmlArr.push('<label class="inline radio" style="color: #bfbfbf">道具开关控制</label>');
                    htmlArr.push('</div></div><div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">默认展示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_list" value="1"' + (e.is_default == 1 ? "checked" : "") + ' >是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_list" value="0"' + (e.is_default == 0 ? "checked" : "") + ' >否</label>');
                    htmlArr.push('<button type="button" class="btn add blue-btn down" onclick="Program.View.opTabMove(this, 1)"> 下移</button>');
                    htmlArr.push('<button type="button" class="btn add blue-btn up" onclick="Program.View.opTabMove(this, 0)"> 上移</button>');
                    htmlArr.push('</div></div></div></li>');
                    break;
                case 3:
                    htmlArr.push('<li data-type="' + e.type + '" data-id="' + e.id + '"><div class="operationDiv"><div class="control-group">');
                    htmlArr.push('<select style="width:90px;" disabled="disabled"><option value="simple-video">活动页</option></select>');
                    htmlArr.push('<input type="text" name="op_display_name" placeholder="" value="' + e.display_name + '" style="margin-left: 4px;">');
                    htmlArr.push('<label name="op_display_name_hint" style="color: #FF0000; display: none;">错误提示</label>');
                    htmlArr.push('<button type="button" class="btn add blue-btn" style="float: right;" onclick="Program.View.opDelete(this,' + e.id + ');"> 删除</button></div>')
                    htmlArr.push('<div class="control-group">');
                    htmlArr.push('<label class="col-xs-2 control-label" style="text-align: left;width: 80px;margin-left:4px;">活动地址：</label>');
                    htmlArr.push('<input type="text" name="text_activity' + e.id + '" placeholder="" value="' + e.url + '"></div>');
                    htmlArr.push('<div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">是否显示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_activity' + e.id + '" value="1"' + (e.is_enable == 1 ? "checked" : "") + '>是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_activity' + e.id + '" value="0"' + (e.is_enable == 0 ? "checked" : "") + '>否</label>');
                    htmlArr.push('</div></div><div class="control-group"><label class="col-xs-2 control-label" style="width:60px;margin-left:4px;">默认展示：</label>');
                    htmlArr.push('<div class="controls" style="margin-left: 0px;">');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_activity' + e.id + '" value="1"' + (e.is_default == 1 ? "checked" : "") + ' >是</label>');
                    htmlArr.push('<label class="radio inline"><input type="radio" name="radio_default_activity' + e.id + '" value="0"' + (e.is_default == 0 ? "checked" : "") + ' >否</label>');
                    htmlArr.push('<button type="button" class="btn add blue-btn down" onclick="Program.View.opTabMove(this, 1)"> 下移</button>');
                    htmlArr.push('<button type="button" class="btn add blue-btn up" onclick="Program.View.opTabMove(this, 0)"> 上移</button>');
                    htmlArr.push('</div></div></div></li>');

                    Program.Config.opActivityNums.remove(e.id + "");
                    break;
                default:
                    break;
            }

            return htmlArr.join("");
        }

        function opTabMove(element, type) {
            var e = $(element);
            var p = e.closest('li');

            // 0: up, 1: down
            if (type == 0) {
                var prev = p.prev();
                if (prev.length) {
                    prev.insertAfter(p);

                    if (p.prev().length == 0) {
                        p.find("button.up").hide();
                        p.find('button.down').show();
                    } else {
                        p.find("button.up").show();
                        p.find('button.down').show();
                    }

                    if (prev.next().length == 0) {
                        prev.find("button.up").show();
                        prev.find("button.down").hide();
                    } else {
                        prev.find("button.up").show();
                        prev.find("button.down").show();
                    }

                }
            } else if (type == 1) {
                var next = p.next();
                if (next.length) {
                    next.insertBefore(p);

                    if (p.next().length == 0) {
                        p.find("button.down").hide();
                        p.find("button.up").show();
                    } else {
                        p.find("button.down").show();
                        p.find("button.up").show();
                    }
                    if (next.prev().length == 0) {
                        next.find("button.down").show();
                        next.find("button.up").hide();
                    } else {
                        next.find("button.down").show();
                        next.find("button.up").show();
                    }
                }
            }
        }

        function opAddActivity() {
            var area = $('#operationTabControlArea');

            var lis = area.find('li');
            if (lis.length >= 6) {
                showTips({ content: "添加失败，最多支持3个活动页面。", type: "error" });
                return;
            }

            var opId = Program.Config.opActivityNums[0];
            //Program.Config.opActivityNums.remove(opId);

            var tabStr = Program.View.makeUpTab({
                'type': '3', 'display_name': '', 'url': '', 'is_enable': '1', 'id': opId, 'is_default': '0'});
            var tab = $.parseHTML(tabStr);


            var last = area.find('li:last-child');
            $(last).find('button.down').show();

            $(last).after(tab);

            $(tab).find('button.down').hide();

            Program.View.opBindDefaultClick($(tab));
            Program.View.opBindDisplayClick($(tab));
            Program.View.opBindKeyupEvent($(tab))

        }

        function opBindDefaultClick(p) {
            var elements = $(p).find('input[name*=radio_default_]')
            $.each(elements, function (i, e) {
                $(e).bind("click", function (event) {
                    var $curTarget = $(event.currentTarget);
                    if ($curTarget.val() == 1) {
                        Program.View.opSetDefaultDisableOthers($curTarget);
                    } else {
                        //Program.View.opSetDefaultFirst();
                    }
                })
            })

        }

        function opBindDisplayClick(p) {
            var elements = $(p).find('input[name*=radio_]')
            $.each(elements, function (i, e) {
                $(e).bind("click", function (event) {
                    var $curTarget = $(event.currentTarget);
                    if ($curTarget.val() == 0) {
                        Program.View.opSetDefaultByDisplay($(event.currentTarget));
                    } else {
                        //Program.View.opSetDefaultFirst();
                    }
                })
            })
        }


        //绑定keyup事件
        function opBindKeyupEvent(p) {
            var elements = $(p).find('input[name*=op_display_name]')
            $.each(elements, function (i, e) {
                $(e).bind("input", function (event) {
                    var $curTarget = $(event.currentTarget);
                    var diplayNameValue = $curTarget.val();
                    var maxLength = 4;
                    if (diplayNameValue.gblen() > (maxLength * 2)) {
                        // 更新 label 提示
                        $curTarget.next().css('display', 'inline').html("超出长度限制，最多支持" + maxLength + "个文字");
                    } else {
                        $curTarget.next().css('display', 'none')
                    }
                })
            })
        }


        function opSetDefaultByDisplay(e) {
            var p = $(e).closest('li');
            p.find('input[name*=radio_default_][value="0"]').prop('checked', true);
        }

        function opSetDefaultDisableOthers(element) {
            var p = $(element).closest('li');
            var lis = p.siblings();

            $.each(lis, function (i, e) {
                $(e).find('input[name*=radio_default_][value="0"]').prop('checked', true);
            })
        }

        function opSetDefaultFirst() {
            var first = $('#operationTabControlArea').find('li:first-child');
            $(first).find('input[name*=radio_default_][value="1"]').prop('checked', true);
        }

        function opDelete(element, id) {
            var e = $(element);
            var p = e.closest('li');


            SystemDialog.queryConfirm("确认删除?", function (flag) {
                if (flag == true) {
                    var isDefault = false;
                    if (p.find('input[name*=radio_default_]:checked').val() == 1) {
                        isDefault = true;
                    }
                    p.remove();
                    Program.Config.opActivityNums.push(id + "");
                    Program.View.opHideUpDownBtn();
                    if (isDefault) {
                        Program.View.opSetDefaultFirst();
                    }
                }
            })

        }

        function opSetDisplayByRelation() {
            var chat_enable = $('input:radio[name=chat_enable]:checked').val();
            var daoju_enable = $('input:radio[name=daojuFlag]:checked').val();

            $('input:radio[name=radio_chat_room][value=' + chat_enable + ']').prop("checked", true);
            $('input:radio[name=radio_list][value=' + daoju_enable + ']').prop("checked", true);

            if (chat_enable == 0) {
                Program.View.opSetDefaultByDisplay($('input:radio[name=radio_chat_room][value="0"]'));
            }

            if (daoju_enable == 0) {
                Program.View.opSetDefaultByDisplay($('input:radio[name=radio_list][value="0"]'));
            }
        }

        function opGetData() {
            var area = $('#operationTabControlArea');
            var lis = area.find('li');
            var data = [];
            var error = "";
            var maxLength = 4;
            $.each(lis, function (i, li) {
                var e = $(li);
                var obj = {};
                switch (parseInt(e.attr('data-type'))) {
                    case 0:
                        obj.type = 0;
                        obj.display_name = e.find('input[name=op_display_name]').val();
                        obj.is_enable = e.find('input:radio[name=radio_chat_room]:checked').val();
                        obj.is_default = e.find('input:radio[name=radio_default_chat_room]:checked').val();
                        if (obj.display_name == "") {
                            showTips({ content: "聊天室名称不能为空", type: "error" });
                            error = "聊天室名称不能为空";
                            return "";
                        }
                        break;
                    case 1:
                        obj.type = 1;
                        obj.display_name = e.find('input[name=op_display_name]').val();
                        obj.is_enable = e.find('input:radio[name=radio_more]:checked').val();
                        obj.is_default = e.find('input:radio[name=radio_default_more]:checked').val();
                        if (obj.display_name == "") {
                            showTips({ content: "看更多名称不能为空", type: "error" });
                            error = "看更多名称不能为空";
                            return "";
                        }

                        break;
                    case 2:
                        obj.type = 2;
                        obj.display_name = e.find('input[name=op_display_name]').val();
                        obj.is_enable = e.find('input:radio[name=radio_list]:checked').val();
                        obj.is_default = e.find('input:radio[name=radio_default_list]:checked').val();
                        if (obj.display_name == "") {
                            showTips({ content: "排行榜名称不能为空", type: "error" });
                            error = "排行榜名称不能为空";
                            return "";
                        }
                        break;
                    case 3:
                        obj.type = 3;
                        obj.display_name = e.find('input[name=op_display_name]').val();
                        obj.is_enable = e.find('input:radio[name*=radio_activity]:checked').val();
                        obj.is_default = e.find('input:radio[name*=radio_default_]:checked').val();
                        obj.url = e.find('input[name*=text_activity]').val();
                        obj.id = e.attr('data-id');
                        if (obj.display_name == "" || obj.url == "") {
                            showTips({ content: "活动页名称或地址不能为空", type: "error" });
                            error = "活动页名称或地址不能为空";
                            return "";
                        }

                        break;
                    default:
                        break;
                }

                if (obj.display_name.gblen() > (maxLength * 2)) {
                    showTips({content: "超出长度限制，最多支持" + maxLength + "个文字", type: "error"});
                    error = "超出长度限制，最多支持" + maxLength + "个文字";
                    return "";
                }
                data.push(obj);
            });

            if (error != "") {
                return "";
            }

            return JSON.stringify(data);

        }

        function showCategoriesDlg() {

            var $container = $("#categories-dlg");

            $container.dialog({
                title: '对应列表分类',
                appendTo: null,
                modal: true,
                width: 450,
                //  height:380,
                //      maxHeight: 380,
                position: ['top', 'top+20'],
                buttons: [
                    {
                        text: '确定', //  提交分类
                        click: function () {
                            var tags = [],
                                ids = [];
                            $.each($("#category-val").find('span'), function () {
                                ids.push($(this).attr("data-tag-id"));
                                tags.push($(this).attr("data-tag-label"));
                            });
                            //console.log(ids);
                            //console.log(tags);
                            var tags = $('.tagshow').text(tags.join(','));
                            var ids = $('input[name="tag"]').val(ids.join(','));
                            $(this).dialog('close');
                        }
                    },
                    {
                        text: '取消',
                        click: function () {
                            $(this).dialog('close');
                        }
                    }
                ],

                open: function () {
                    $("#categories-dlg").find(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                },
                close: function () {

                }

            });

            var $tmpl = $("#categories");

            Program.Dao.getParentCategories('', function () {
                $container.html($tmpl.tmpl({
                    parentCategory: Program.Config.PCAT
                }));
            });


        }

        // 显示已选分类
        function _showHasSelectedCat() {
            var tags = $('.tagshow').text().split(',');
            var ids = $('input[name=tag]').val().split(',');
            var tag_span = '';
            if (tags == '') return;
            $.each(tags, function (i, item) {
                tag_span = tag_span + '<span data-tag-id="' + ids[i] + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + item + '">' + item + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>';
            });
            $("#category-val").append(tag_span);

        }

        return {
            fillForm: fillForm,
            fillPuYuOnClick: fillPuYuOnClick,
            initRelationDataArea: initRelationDataArea,
            initDialog: initDialog,
            initEditPicZone: initEditPicZone,
            makeUpTab: makeUpTab,
            opTabMove: opTabMove,
            opAddActivity: opAddActivity,
            opHideUpDownBtn: opHideUpDownBtn,
            opDelete: opDelete,
            opGetData: opGetData,
            opBindDefaultClick: opBindDefaultClick,
            opBindDisplayClick: opBindDisplayClick,
            opBindKeyupEvent: opBindKeyupEvent,
            opSetDefaultFirst: opSetDefaultFirst,
            opSetDefaultByDisplay: opSetDefaultByDisplay,
            opSetDefaultDisableOthers: opSetDefaultDisableOthers,
            opSetDisplayByRelation: opSetDisplayByRelation,
            initOperationTabControlArea: initOperationTabControlArea,
            showCategoriesDlg: showCategoriesDlg,
            _showHasSelectedCat: _showHasSelectedCat,
            fillInitDataByOAData: fillInitDataByOAData
        }
    })();
    Program.Formatter = (function () {
        function reutrnNull() {
            // return "unknown"
            return "";
        }

        function transToEpisodeGrade(live, liveABC) {
            var baseValue = 100;
            if (live == "" || liveABC == "") {
                return "";
            }
            live = parseInt(live);
            liveABC = parseInt(liveABC);
            baseValue += live + (liveABC - 1) * 10;
            return baseValue
        }

        function chiefEditorApprovalStatus(value) {
            switch (value) {
                case "unchecked":
                    return "待审核";
                case "interrupt":
                    return "待审核";
                case "checked":
                    return "总编室已确认";
                default :
                    return "";
            }
        }

        function formatDate(myDate) {
            var year = myDate.getFullYear();
            var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
            var day = ("0" + myDate.getDate()).slice(-2);
            var h = ("0" + myDate.getHours()).slice(-2);
            var m = ("0" + myDate.getMinutes()).slice(-2);
            var s = ("0" + myDate.getSeconds()).slice(-2);
            return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
        }

        function transLongToDate(time) {
            if (time == null) {
                return "";
            }
            var tempDate = new Date();
            tempDate.setTime(time);
            return formatDate(tempDate);
        }

        function getFormatCopyRightEndTime(checkValue) {
            if (checkValue == null) {
                return reutrnNull();
            }
            if (typeof( checkValue ) == "string") {
                return checkValue;
            }
            if (checkValue <= 0) {
                return "---";
            } else {
                var date = new Date();
                date.setTime(parseInt(checkValue))
                return  formatDate(date);
            }
        }

        function getFormatPurchase(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                case -100:
                    return "免费";
                case 1:
                case 2:
                case 3:
                    return "收费";
                default:
                    return checkValue + ""
            }

        }

        function getFormatPublishStatus(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                    return "未发布";
                case 1:
                    return "已发布";
                case 2:
                    return "页面下线";
                case 3:
                    return "页面备用"
                default:
                    return checkValue + "";
            }
        }

        function getFormatMaterial($target) {
            var retData = {
                "area": "bj",
                //    "id":$target.data("data").id,
                "fromType": "0",
                "location": $target.data("spath"),
                "width": $target.data("width"),
                "height": $target.data("height")
            }
            if ($target.data("data") != null && $target.data("data").id > 0) {
                retData.id = $target.data("data").id
            }
            return retData
        }

        function getFormatCrop(cropTarget) {
            return {
                "materialLocation": cropTarget.spath,
                "editInfo": {
                    "cutPosition": [cropTarget.x1, cropTarget.y1, cropTarget.y2 - cropTarget.y1, cropTarget.x2 - cropTarget.x1].join(","),
                    "scale": cropTarget.w + ":" + cropTarget.h
                }
            }
        }

        function getTemplate(item) {
            var formatArr = [];
            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
            formatArr.push('<span class="contract-width120">' + getFormatCopyRightEndTime(item.copyrightEndTime) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPurchase(item.isPurchase) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPublishStatus(item.pagePublishStatus) + '</span>');
            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
        }

//        is_valid：0无效，1有效
//
//        matchStage：0=未知  1=决赛 2=半决赛 3=三四名决赛 4=1/4决赛 5=1/8决赛 6=小组赛 7=复活赛   8=排名赛 9=资格赛 10=开幕式 11=闭幕式 12颁奖仪式  13=淘汰赛
//        matchType：0=未知  1=双反对抗  2=多方排位

//        function getSportValid(value) {
//            switch (value) {
//                case 0:
//                    return "无效";
//                case 1:
//                    return "有效";
//                default :
//                    return "unknown:" + value;
//            }
//        }

        function getSportMatchStage(value) {
            switch (value) {
                case 0:
                    return "未知";
                case 1:
                    return "决赛";
                case 2:
                    return "半决赛";
                case 3:
                    return "三四名决赛";
                case 4:
                    return "1/4决赛";
                case 5:
                    return "1/8决赛";
                case 6:
                    return "小组赛";
                case 7:
                    return "复活赛";
                case 8:
                    return "排名赛";
                case 9:
                    return "资格赛";
                case 10:
                    return "开幕式";
                case 11:
                    return "闭幕式";
                case 12:
                    return "颁奖仪式";
                case 13:
                    return "淘汰赛";
                default :
                    return "unknown:" + value;
            }
        }

        function associatedLive(value) {
            if (value == null || value === "") {
                return "未绑定"
            }
            return "已绑定"
        }

//        function getSportMatchType(value) {
//            switch (value) {
//                case 0:
//                    return "未知";
//                case 1:
//                    return "双反对抗";
//                case 1:
//                    return "多方排位";
//                default :
//                    return "unknown:" + value;
//            }
//        }

        return {
            copyRight: getFormatCopyRightEndTime,
            publishStatus: getFormatPublishStatus,
            purchase: getFormatPurchase,
            imageCrop: getFormatCrop,
            imageMaterial: getFormatMaterial,
            getTemplate: getTemplate,
            formatDate: formatDate,

            //      sportValid: getSportValid,
            sportMatchStage: getSportMatchStage,
            //      sportMatchType: getSportMatchType,
            transLongToDate: transLongToDate,
            associatedLive: associatedLive,
            chiefEditorApprovalStatus: chiefEditorApprovalStatus,
            transToEpisodeGrade: transToEpisodeGrade
        }
    })();
    Program.Action = (function () {
        function programRun() {
            var tasks = [];
            var param_fatherId = Com.url.getParameter("fatherId");
            tasks.push(Program.Task.getChannel(param_fatherId));
            tasks.push(Program.Task.getLiveProgramType());
            tasks.push(Program.Task.getLiveTmpOtherType());
            tasks.push(Program.Task.getGradeType());
            tasks.push(Program.Task.getLegoChannelType());

            var param_id = Com.url.getParameter("id");
            var param_from = Com.url.getParameter("from");
            if (param_id != null) {
                Program.memo.id = parseInt(param_id);
                tasks.push(Program.Task.getTargetName(param_id));
            } else {
                if (param_fatherId != null) {
                    Program.memo.fatherId = parseInt(param_fatherId);
                }
            }
            if (param_from != null) {
                Program.memo.from = param_from;
            }

            $.each(tasks, function (index, task) {
                Program.ajaxManager.push(task.regName, task.options);
            })
            Program.ajaxManager.startLoad();
        }

        function programInit() {
            Program.ajaxManager.afterLoadComplete(function () {
                var channelEntity = Program.Dao.getChannel();
                if (channelEntity == null) {
                    return
                }
                if (channelEntity.liveType == 2) {
                    setTimeout(function () {
                        var task = Program.Task.getLegoCategory()
                        Program.ajaxManager.push(task.regName, task.options);
                        Program.ajaxManager.afterLoadComplete(function () {
                            console.log(" route 2 init channelEntity.liveType ")
                            Program.Task.initComplete();
                        });
                        Program.ajaxManager.startLoad();

                    }, 300)
                } else {
                    console.log(" route normal channelEntity.liveType ")
                    Program.Task.initComplete();
                }
            })
        }


        return {
            programRun: programRun,
            programInit: programInit
        }
    })();
})

$(document).ready(function () {
    Array.prototype.remove = function () {
        var what, a = arguments, L = a.length, ax;
        while (L && this.length) {
            what = a[--L];
            while ((ax = this.indexOf(what)) !== -1) {
                this.splice(ax, 1);
            }
        }
        return this;
    };

    Program.Action.programInit();
    Program.Action.programRun();
})

$(document).ready(function () {
    var $imgcrop = $("#AlbumEditScreenCorp");
    var $uploadBtn = $imgcrop.find('input.uploadButton');
    var $slideshow = $imgcrop.find('.slideshow');
    $slideshow.gallery({
        thumbnail: '.item',
        prevButton: $slideshow.find('button.left'),
        nextButton: $slideshow.find('button.right')
    });
    $imgcrop.imagecrop({
        'gallery': '.gallery',
        'cropimg': '.cropimg',
        'results': '.results'
    });
    $uploadBtn.val("");
    $uploadBtn.bind("click", function (event) {
        console.log("click");
    })
    $uploadBtn.bind("change", function (event) {
        var file = $uploadBtn[0].files[0];
        var url = Com.file.getObjectURL(file)
        var checkFileType = Com.file.getExt(file.name);
        var acceptTypes = $uploadBtn[0].accept
        if (acceptTypes.indexOf("." + checkFileType) == -1) {
            showTips({
                content: "只允许提交类型为" + acceptTypes + "的文件",
                type: "error"
            })
            return;
        }
        if (file.size > 1024 * 1024 * 5) {
            showTips({
                content: "上传文件大小不能超过5M",
                type: "error"
            })

            return;
        }
        var headers = {
            businessType: "image",
            filesize: file.size,
            role: "epg_image",
            filetype: Com.file.getExt(file.name),
            producttype: "ppc",
            Location: "sh"
        }

        var options = {
            headers: headers,
            file: file
        };
        Program.Model.startUpload(file);
        Program.Model.startRequestFile(options, requestOver);

    })

    function requestOver(data) {
        console.log("request file:" + data);
        if (data.code == 'A00000') {
            Program.Model.startUploadFile(data, uploadOver);
        } else {
            console.log(data.msg);
        }
    }

    function uploadOver(data) {
        if (data.code == 'A00000') {
            var $imgcrop = $("#AlbumEditScreenCorp");
            $imgcrop.imagecrop("addImages", [
                {url: data.data.httpInnerUrl, "spath": data.data["file_path"]}
            ]);
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            $uploadBtn.val("");
        } else {
            console.log(data.msg);
        }
    }
})